package com.dragon.app.ykd.service;

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.*;

import com.marvels.approve.loan.dto.McamAcLoanApplyImageInfo;
import com.marvels.approve.process.dao.AttachmentInfoDao;
import com.marvels.common.dto.MarvelsResultDTO;
import com.marvels.financial.loan.api.IProductInfoApi;
import com.marvels.financial.loan.dao.McfeFundSourceRateDao;
import com.marvels.financial.loan.dto.*;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.RandomStringUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.dragon.app.commons.constant.ContactsTypeEnum;
import com.dragon.app.commons.constant.ErrorCode;
import com.dragon.app.commons.dto.JiaYinJinKApplyLoanDTO;
import com.dragon.app.commons.dto.JiaYinJinKContactDTO;
import com.dragon.app.commons.dto.ProductApplyDTO;
import com.dragon.app.commons.utils.FileDragonUtils;
import com.dragon.app.commons.utils.UserUtils;
import com.dragon.app.marvel.core.AsyncCallApi;
import com.dragon.app.um.vo.JsonResult;
import com.dragon.app.ykd.constant.ApplyNode;
import com.dragon.app.ykd.constant.ExtensionResult;
import com.dragon.app.ykd.constant.ExtensionType;
import com.dragon.app.ykd.dto.AcLenderConfig;
import com.dragon.app.ykd.dto.AcLoanApplyNode;
import com.dragon.app.ykd.dto.LoanExtensionRecoreds;
import com.dragon.app.ykd.dto.SaveLinkmansDTO;
import com.dragon.app.ykd.dto.UserDataDTO;
import com.dragon.common.constant.Constant;
import com.dragon.common.repository.mybatis.paginator.domain.Order;
import com.dragon.common.repository.mybatis.paginator.domain.PageBounds;
import com.dragon.common.utils.Collections3;
import com.dragon.loan.entity.AcApplyEnvironmentInfo;
import com.dragon.loan.entity.AcLoanApplyInfo;
import com.dragon.loan.entity.AcLoanApplyLinkman;
import com.dragon.loan.repository.AcLenderConfigMapper;
import com.dragon.loan.repository.AcLoanApplyInfoRepository;
import com.dragon.loan.repository.AcLoanApplyLinkmanRepository;
import com.dragon.loan.service.AcLoanApplyInfoExtDragonService;
import com.dragon.loan.service.AcLoanApplyInfoServiceImpl;
import com.dragon.loan.service.BlackInfoIDragonService;
import com.dragon.loan.service.LoanInfoIDragonService;
import com.fintech.common.enums.ReturnCode;
import com.fintech.common.util.RedisUtils;
import com.fintech.common.vo.FintechResult;
import com.fintech.user.entity.RealNameAuthentication;
import com.fintech.user.entity.User;
import com.fintech.user.service.RealNameAuthenticationService;
import com.marvels.approve.common.service.ProductConsumerService;
import com.marvels.approve.loan.dto.McamLoanApplyInfoDTO;
import com.marvels.approve.mqueues.service.ApproveILoanApplyDataSynchronizeService;
import com.marvels.approve.process.dto.McptProductInfoDTO;
import com.marvels.approve.process.dto.ProtocolTemplateInfoDTO;
import com.marvels.common.constants.PayContants;
import com.marvels.common.dto.pay.MarvelsPayResultDTO;
import com.marvels.common.dto.pay.McfePaymentUserBindCard;
import com.marvels.common.exception.MarvelsBusinessException;
import com.marvels.common.utils.CacheUtils;
import com.marvels.common.utils.MarvelsLogUtil;
import com.marvels.common.utils.ServerProperties;
import com.marvels.financial.loan.service.ExtensionFunctionApi;
import com.marvels.financial.pay.service.PayService;
import com.marvels.loanapply.api.MclaLinkmanMobileApi;
import com.marvels.loanapply.dto.MclaLoanApplyLinkmanDTO;
import com.marvels.product.productmanage.dto.McptProductTypeDto;
import com.marvels.product.productmanage.service.ProductTypeService;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.lang.Validator;
import cn.hutool.core.util.IdcardUtil;
import cn.hutool.core.util.StrUtil;

@Service("clientAppService")
public class ClientAppServiceImpl implements ClientAppService {

	@Autowired
	private LoanInfoIDragonService loanInfoIDragonService;
	@Autowired
	private RealNameAuthenticationService realNameAuthenticationService;

	@Autowired
	private ProductConsumerService productConsumerService;

	@Autowired
	private BlackInfoIDragonService blackInfoIDragonService;

	@Autowired
	private AcLoanApplyNodeService acLoanApplyNodeService;
	@Autowired
	private AcLenderConfigMapper acLenderConfigMapper;
	@Autowired
	private AcLoanApplyInfoExtDragonService acLoanApplyInfoExtDragonService;
	@Autowired
	private AcLoanApplyInfoRepository acLoanApplyInfoRepository;
	@Autowired
	private ProductTypeService productTypeService;
	@Autowired
	private ExtensionFunctionApi extensionFunctionApi;
	@Autowired
	private AsyncCallApi asyncCallApi;
	@Autowired
	private MclaLinkmanMobileApi mclaLinkmanMobileApi;
	@Autowired
	private AcLoanApplyInfoServiceImpl acLoanApplyInfoService;
	@Autowired
	private PayService payService;
	@Autowired
	private AcLoanApplyLinkmanRepository loanApplyLinkmanRepository;

	@Autowired
	private ApproveILoanApplyDataSynchronizeService loanApplyDataSynchronizeService;

	@Autowired
	private AttachmentInfoDao attachmentInfoDao;

	@Value("${reloan.days}")
	private long days;

	@Value("${config.properties.path}")
	private String configPropertiesPath;
	@Autowired
	private IProductInfoApi iProductInfoApi;


	@Override
	public FintechResult saveContactInfo(UserDataDTO userData,Integer userId) {
		if (userData == null || StringUtils.isEmpty(userData.getAddress()) || StringUtils.isEmpty(userData.getCityName())
				|| StringUtils.isEmpty(userData.getAreaName())) {
			return FintechResult.getResult(ErrorCode.FAIL, "居住地址不全", null);
		}else if(StringUtils.isEmpty(userData.getCompanyCityName()) || StringUtils.isEmpty(userData.getCompanyAreaName())
				|| StringUtils.isEmpty(userData.getCompanyAddress())) {
			return FintechResult.getResult(ErrorCode.FAIL, "工作地址不全", null);
		}

		if(StringUtils.isBlank(userData.getMarriageId())) {
			return FintechResult.getResult(ErrorCode.FAIL, "婚姻状况不可为空", null);
		}else if(StringUtils.equalsIgnoreCase(userData.getMarriageId(), "2") && (
				StringUtils.isEmpty(userData.getMateName()) || StringUtils.isEmpty(userData.getMateMobile())) ) {
			//婚姻请款为已婚且配偶姓名或手机号为空时返回
			return FintechResult.getResult(ErrorCode.FAIL, "配偶姓名和手机号不可为空", null);
		}

		//1 验证是否实名认证
		RealNameAuthentication realNameAuthentication = realNameAuthenticationService.queryByUserId(userId);
		if (null == realNameAuthentication) {
			return FintechResult.getResult(ErrorCode.NO_VERIFY, "", null);
		}

		//2 获取当前贷款申请编号
		String loanId = loanInfoIDragonService.selectCustApplyingLoanId(realNameAuthentication.getIdentityCardNo());
		if(StringUtils.isBlank(loanId)) {
			return FintechResult.getResult(ErrorCode.FAIL, "请先确认产品、期数、金额后在提交", null);
		}

		//3 更新工作地址、居住地址、婚姻信息
		AcLoanApplyInfo updateInfo = new AcLoanApplyInfo();
		BeanUtils.copyProperties(userData, updateInfo);
		updateInfo.setLoanId(loanId);

		//获取已绑定的银行卡信息
		String currentChannel  = ServerProperties.getValue(configPropertiesPath, "common.properties", "payment_channel");
		MarvelsPayResultDTO bankResultData = payService.queryBankList(realNameAuthentication.getIdentityCardNo(), currentChannel);
		if(null == bankResultData || null == bankResultData.getData()) {

		}

		AcLoanApplyInfo acLoanApplyInfo = loanInfoIDragonService.queryLoanBasicInfo(loanId);

		//设置还款卡和收款卡
		if(StringUtils.isBlank(acLoanApplyInfo.getReceiveAcct()) ||
				StringUtils.isBlank(acLoanApplyInfo.getRepayAcct())) {
			List<McfePaymentUserBindCard> userBindCards = (List<McfePaymentUserBindCard>)bankResultData.getData();
			if(CollectionUtils.isEmpty(userBindCards)) {
				return FintechResult.getResult(ErrorCode.FAIL, "请先完成银行卡绑定后在提交", null);
			}

			McfePaymentUserBindCard userBindCard = userBindCards.get(0);

			for (McfePaymentUserBindCard mcfePaymentUserBindCard : userBindCards) {
				if("1".equals(mcfePaymentUserBindCard.getDefaultCard())) {
					userBindCard = mcfePaymentUserBindCard;
					break;
				}
			}
			updateInfo.setReceiveAcct(userBindCard.getBankCardNo());
			updateInfo.setReceiveAcctName(userBindCard.getCustName());
			updateInfo.setReceiveBankName(userBindCard.getBankName());
			updateInfo.setRepayAcct(userBindCard.getBankCardNo());
			updateInfo.setRepayAcctName(userBindCard.getCustName());
			updateInfo.setRepayBankName(userBindCard.getBankName());
		}
		// 新增影像文件保存

		if(userData.getIdentityImg()!=null)
		{
			McamAcLoanApplyImageInfo mcamAcLoanApplyImageInfo = new McamAcLoanApplyImageInfo();
			mcamAcLoanApplyImageInfo.setAtmtType("A");
			mcamAcLoanApplyImageInfo.setAtmtTypeName("其他身份证明");
			mcamAcLoanApplyImageInfo.setUploadTime(new Date());
			mcamAcLoanApplyImageInfo.setFileLocation(userData.getIdentityImg());
			mcamAcLoanApplyImageInfo.setLoanId(loanId);
			mcamAcLoanApplyImageInfo.setCreatedBy("system");
			mcamAcLoanApplyImageInfo.setCreatedDate(Calendar.getInstance().getTime());
			mcamAcLoanApplyImageInfo.setUpdatedBy("system");
			mcamAcLoanApplyImageInfo.setUpdatedDate(Calendar.getInstance().getTime());
			attachmentInfoDao.insertAttachmentInfo(mcamAcLoanApplyImageInfo);
		}
		if(userData.getCreditImg()!=null)
		{
			McamAcLoanApplyImageInfo mcamAcLoanApplyImageInfo = new McamAcLoanApplyImageInfo();
			mcamAcLoanApplyImageInfo.setAtmtType("A");
			mcamAcLoanApplyImageInfo.setAtmtTypeName("征信报告");
			mcamAcLoanApplyImageInfo.setUploadTime(new Date());
			mcamAcLoanApplyImageInfo.setFileLocation(userData.getCreditImg());
			mcamAcLoanApplyImageInfo.setLoanId(loanId);
			mcamAcLoanApplyImageInfo.setCreatedBy("system");
			mcamAcLoanApplyImageInfo.setCreatedDate(Calendar.getInstance().getTime());
			mcamAcLoanApplyImageInfo.setUpdatedBy("system");
			mcamAcLoanApplyImageInfo.setUpdatedDate(Calendar.getInstance().getTime());
			attachmentInfoDao.insertAttachmentInfo(mcamAcLoanApplyImageInfo);
		}
		if(userData.getTradeImg()!=null)
		{
			McamAcLoanApplyImageInfo mcamAcLoanApplyImageInfo = new McamAcLoanApplyImageInfo();
			mcamAcLoanApplyImageInfo.setAtmtType("A");
			mcamAcLoanApplyImageInfo.setAtmtTypeName("其他交易证明材料");
			mcamAcLoanApplyImageInfo.setUploadTime(new Date());
			mcamAcLoanApplyImageInfo.setFileLocation(userData.getTradeImg());
			mcamAcLoanApplyImageInfo.setLoanId(loanId);
			mcamAcLoanApplyImageInfo.setCreatedBy("system");
			mcamAcLoanApplyImageInfo.setCreatedDate(Calendar.getInstance().getTime());
			mcamAcLoanApplyImageInfo.setUpdatedBy("system");
			mcamAcLoanApplyImageInfo.setUpdatedDate(Calendar.getInstance().getTime());
			attachmentInfoDao.insertAttachmentInfo(mcamAcLoanApplyImageInfo);
		}
		if(userData.getObjectImg()!=null)
		{
			McamAcLoanApplyImageInfo mcamAcLoanApplyImageInfo = new McamAcLoanApplyImageInfo();
			mcamAcLoanApplyImageInfo.setAtmtType("A");
			mcamAcLoanApplyImageInfo.setAtmtTypeName("实物证明材料");
			mcamAcLoanApplyImageInfo.setUploadTime(new Date());
			mcamAcLoanApplyImageInfo.setFileLocation(userData.getObjectImg());
			mcamAcLoanApplyImageInfo.setLoanId(loanId);
			mcamAcLoanApplyImageInfo.setCreatedBy("system");
			mcamAcLoanApplyImageInfo.setCreatedDate(Calendar.getInstance().getTime());
			mcamAcLoanApplyImageInfo.setUpdatedBy("system");
			mcamAcLoanApplyImageInfo.setUpdatedDate(Calendar.getInstance().getTime());
			attachmentInfoDao.insertAttachmentInfo(mcamAcLoanApplyImageInfo);
		}

		MarvelsLogUtil.getInstance().info("loanId："+updateInfo.getLoanId()+"，申请提交更新数据参数：" + JSON.toJSONString(updateInfo));
		acLoanApplyInfoService.updateApply(updateInfo);
		return doApprove(loanId);
	}

	/**
	 * 保存用户对应的联系人信息
	 *
	 * @param acLinkmanMobiles
	 * @param accessToken
	 * @param idFintechUmUser
	 * @return
	 */
	@Override
	public FintechResult saveLinkmans(List<SaveLinkmansDTO> acLinkmanMobiles,Integer userId) {
//		if (acLinkmanMobiles == null || acLinkmanMobiles.isEmpty()) {
//			return FintechResult.getResult(ErrorCode.SUCCESS, "操作成功", null);
//		}
//
//		// 组装联系人list
//		List<AcLinkmanMobile> acLinkmanMobileList = new ArrayList<>();
//
//		//1 验证是否实名认证
//		ResultData<Boolean> selectByUserIdResponse = realNameAuthenticationService.selectByUserId(userId);
//		if (!selectByUserIdResponse.getData()) {
//			return FintechResult.getResult(ErrorCode.NO_VERIFY, "", null);
//		}
//
//		//2 获取当前贷款申请编号
//		RealNameAuthentication realNameAuthentication = realNameAuthenticationService.queryByUserId(userId);
//		String loanId = loanInfoIDragonService.selectCustApplyingLoanId(realNameAuthentication.getIdentityCardNo());
//
//		Map<String, Object> linkMans = thirdAcLinkmanMobileService.selectLinkManInfo(String.valueOf(userId));
//
//		//3 从请求中解析出 待保存的  联系人列表和 临时数据
//		for (SaveLinkmansDTO saveLinkmansDTO : acLinkmanMobiles) {
//			AcLinkmanMobile acLinkmanMobile = new AcLinkmanMobile();
//			String number = saveLinkmansDTO.getNumber();
//			String name = saveLinkmansDTO.getName();
//			if (StrUtil.isEmpty(number)) {
//				continue;
//			}
//			number = number.replaceAll("[^0-9]+", "");
//			if (number.length() > 11) {
//				number = number.substring(number.length() - 11);
//			}
//
//			//3.1 生成联系人
//			acLinkmanMobile.setLinkmanMobileNum(StrUtil.isEmpty(number) ? number : (number.length() > 50 ? number.substring(0, 50) : number));
//			acLinkmanMobile.setLinkmanName(StrUtil.isEmpty(name) ? name : (name.length() > 50 ? name.substring(0, 50) : name));
//			acLinkmanMobile.setCreatedBy(userId+"");
//			acLinkmanMobile.setUpdatedBy(userId+"");
//			acLinkmanMobile.setUserId(userId+"");
//
//			// 如果当前号码不存在，才新增
//			if(linkMans == null || linkMans.get(acLinkmanMobile.getLinkmanMobileNum()) == null){
//				acLinkmanMobileList.add(acLinkmanMobile);
//			}
//		}
//		try {
//			if(acLinkmanMobileList.size() > 0){
//				thirdAcLinkmanMobileService.saveLinkmanInfos(acLinkmanMobileList);
//			}
//		} catch (Exception e) {
//			MarvelsLogUtil.getInstance().error("=====save/linkmans=====" + loanId + JSONUtil.toJsonStr(acLinkmanMobileList), e);
//			return FintechResult.getResult(ErrorCode.FAIL, "系统异常", null);
//		}
		return FintechResult.getResult(ErrorCode.SUCCESS, "操作成功", null);
	}


	/**
	 * 验证是否有正在进件的工单
	 *
	 * @param shortUrl
	 * @param response
	 * @return
	 */
	@Override
	public FintechResult loanVerify(String accessToken, String idFintechUmUser) {
		Map<String, String> resultMap = new HashMap<>();
		MarvelsLogUtil.getInstance().info("1.ClientAppServiceImpl.loanVerify" + System.currentTimeMillis());
		try {
			// 调用接口根据userId 来获取这个用户所对应的实名验证的信息
			User user = UserUtils.getUser(accessToken, idFintechUmUser);
			if (user == null) {
				return FintechResult.getResult(ReturnCode.tokenInvalid.getErrorCode(), "登录超时，请重新登录！", null);
			}
			Integer userId = user.getId();
			String cardNo = user.getCardNo();
			// 判断是否已经实名验证了 ， 如果没有则驳回
			if(StrUtil.isEmpty(cardNo)){
				RealNameAuthentication realNameAuthentication = realNameAuthenticationService.queryByUserId(userId);
				if(realNameAuthentication != null){
					cardNo = realNameAuthentication.getIdentityCardNo();
				}
			}
			MarvelsLogUtil.getInstance().info("2.ClientAppServiceImpl.loanVerify" + System.currentTimeMillis());

			//如果身份证不存在缓存且不存在数据，则判定未做实名制
			if(StrUtil.isEmpty(cardNo)){
				// 禁止申請的配置
//				Map<String, String> applyConfig = acLoanApplyInfoRepository.getAppConfigByKey("prohibit_apply");
//				MarvelsLogUtil.getInstance().info("applyLoan applyConfig:" + JSONObject.toJSONString(applyConfig));
//				if(applyConfig != null && "0".equals(applyConfig.get("state").toString())){
//					return FintechResult.getResult(ErrorCode.FAIL, applyConfig.get("config_value"), null);
//				}

				// 是否禁止自然流量申请
//				Map<String, String> isApply = clientUserService.isProhibitZrllApply(user.getId(), user.getChannelCode());
//				if("-1".equals(isApply.get("code"))){
//					return FintechResult.getResult(ErrorCode.FAIL, isApply.get("msg"), null);
//				}

				return FintechResult.getResult(ErrorCode.NO_VERIFY, "", null);
			}
			// 判断这个用户是否是第一次进件，如果不是则返回之前订单信息
//			String applyingStatus = loanInfoIDragonService.selectCustApplyingStatus(cardNo);
//			if (StrUtil.isNotEmpty(applyingStatus)) {
//				applyingStatus = applyingStatus.trim();
//				// 判断是否处于已放款状态
//				if ("D01".contains(applyingStatus)) {
//					return FintechResult.getResult(ErrorCode.REPETITION_COMMIT_PAYED, "", null);
//				}
//				return FintechResult.getResult(ErrorCode.LOAN_PROGRESSING, "", null);
//			}
//			MarvelsLogUtil.getInstance().info("3.ClientAppServiceImpl.loanVerify" + System.currentTimeMillis());

			Map<String, String> reloanMap = getReloanMap(cardNo);
//			MarvelsLogUtil.getInstance().info("4.ClientAppServiceImpl.loanVerify" + System.currentTimeMillis());
			if (reloanMap != null && reloanMap.keySet().size()>0) {
				resultMap.putAll(reloanMap);
			}

		} catch (Exception e) {
			MarvelsLogUtil.getInstance().error("=====loan/verify=====", e);
			return FintechResult.getResult(ErrorCode.FAIL, "系统异常", null);
		}
		return FintechResult.getResult(ErrorCode.SUCCESS, "操作成功", resultMap);
	}

	/**
	 * 复贷流程判断<BR>
	 * 1.存在已经结清的单<BR>
	 * 2.与最近结清单的时间间隔不超过30天（以申请时间来判断），这个时间间隔通过配置文件来设置<BR>
	 * 3.复贷的LOANID应当取最近正常申请（非复贷）的贷款编号<BR>
	 */
	private Map<String, String> getReloanMap(String identityCardNo) {
		Map<String, String> resultMap = new HashMap<>();
		try {
			// 查询所有已经结清的单（倒序）
			List<Map<String, Object>> list = loanInfoIDragonService.querySettleLoan(identityCardNo);
			if (Collections3.isEmpty(list)) {
				MarvelsLogUtil.getInstance().info("=====用户第一次进件=====");
				return null;
			}

			MarvelsLogUtil.getInstance().info("=====开始判断用户是否复贷=====, list=" + list);
				// 取最近正常申请的贷款编号作为复贷LOANID
			for (Map<String, Object> map : list) {
				if (!"1".equals(map.get("reloanFlag"))) {
					// 复贷标识reLoanFlag：1表示复贷
					resultMap.put("reloanFlag", "1");
					resultMap.put("reloanId", map.get("loanId") + "");
					return resultMap;
				}
			}
		} catch (Exception ex) {
			// 不影响流程
			MarvelsLogUtil.getInstance().error("=====复贷流程异常=====", ex);
		}
		return null;
	}


	/**
	 * 判断该产品是否需要点亮身份墙
	 *
	 * @param inStr：需验证的产品id
	 *            str：配置文件中的产品id
	 * @return
	 */
	private boolean isNeedGetDataInfo(String inStr, String str) {
		boolean rtnbl = false;
		if (StrUtil.isNotEmpty(str)) {
			String[] strSplit = str.split(",");
			if (strSplit.length > 0) {
				for (String productStr : strSplit) {
					if (productStr.equals(inStr)) {
						rtnbl = true;
						break;
					}
				}
			}
		}
		return rtnbl;
	}


	/**
	 * 客户app第一次进件 立即申请<br>
	 * 只允许进件线上
	 * @param shortUrl
	 * @param response
	 * @return
	 */
	@Override
	public FintechResult applyLoan(ProductApplyDTO productApplyDTO, AcApplyEnvironmentInfo acApplyEnvironmentinfo,String accessToken, String idFintechUmUser) {
		MarvelsLogUtil.getInstance().info("接受请求apply/loan,进件参数:"+JSON.toJSONString(productApplyDTO)+",环境信息:"+JSON.toJSONString(acApplyEnvironmentinfo));

		Map<String, String> resultMap = null;
		User user = UserUtils.getUser(accessToken, idFintechUmUser);
		try {
			if (user == null) {
				return FintechResult.getResult(ReturnCode.tokenInvalid.getErrorCode(), "登录超时，请重新登录！", null);
			}
			//1.判断是否已经实名验证,如果没有则驳回
			RealNameAuthentication realNameAuthentication = realNameAuthenticationService.queryByUserId(user.getId());
			if (realNameAuthentication == null) {
				return FintechResult.getResult(ErrorCode.NO_VERIFY, "请先去实名验证", null);
			}
			MarvelsLogUtil.getInstance().info("1.ClientAppServiceImpl.applyLoan" + System.currentTimeMillis());

			//2.是否在本地黑名单
			String blackListVerifyNew = loanInfoIDragonService.blackListVerifyNew(realNameAuthentication.getIdentityCardNo(), user.getMobileNo());
			if (StrUtil.isNotEmpty(blackListVerifyNew)) {//如果在本地黑名单,则直接决策拒绝
				return FintechResult.getResult(ErrorCode.LIMIT_CALCULATE_DEFEATED, "您暂时不符合我们公司的申请条件", resultMap);
			}
			MarvelsLogUtil.getInstance().info("2.ClientAppServiceImpl.applyLoan" + System.currentTimeMillis());

			//防止进件数据异常
			if(productApplyDTO.getApplyMoney() == null || productApplyDTO.getProductId() == null){
				return FintechResult.getResult(ErrorCode.FAIL, "系统正忙，请退出APP重试", null);
			}

			//3.是否存在贷款
			String applyingStatus = loanInfoIDragonService.selectCustApplyingStatus(realNameAuthentication.getIdentityCardNo());
			if (StrUtil.isNotEmpty(applyingStatus)) {
				applyingStatus = applyingStatus.trim();
				//3.1 判断是否处于已放款状态
//				if ("D01".contains(applyingStatus)) {
//					return FintechResult.getResult(ErrorCode.REPETITION_COMMIT_PAYED, "有正在还款中的贷款", null);
//				}

				//3.2 判断是否是重复提交贷款申请
				if (Constant.LOAN_STATUS_APPLY.indexOf(applyingStatus) >= 0) {
					return FintechResult.getResult(ErrorCode.REPETITION_COMMIT, "重复提交贷款申请，请前往进度查询查看", null);
				}
				//3.3 处于待放款状态
//				return FintechResult.getResult(ErrorCode.REPETITION_COMMIT_PAYING, "有待放款申请", null);
			}
			MarvelsLogUtil.getInstance().info("3.ClientAppServiceImpl.applyLoan" + System.currentTimeMillis());

			//4.保存贷款信息
			String loanId = loanInfoIDragonService.generateLoanId();
			AcLoanApplyInfo acLoanApplyInfo = ProductApplyDTO.getAcLoanApplyInfo(productApplyDTO,realNameAuthentication);
			MarvelsLogUtil.getInstance().info("4.ClientAppServiceImpl.applyLoan" + System.currentTimeMillis());

			acLoanApplyInfo.setLoanId(loanId);

			//5.查询产品类型是否存在
			McptProductTypeDto mcptProducTypeDto = new McptProductTypeDto();
			mcptProducTypeDto.setId(productApplyDTO.getProductId().intValue());
			mcptProducTypeDto = productTypeService.queryOnlineProduct(mcptProducTypeDto);

			if(StringUtils.isBlank(mcptProducTypeDto.getProductType())) {
				return FintechResult.getResult(ErrorCode.FAIL, "申请产品已下线，请确认", null);
			}
			acLoanApplyInfo.setProductType(mcptProducTypeDto.getProductType());
			acLoanApplyInfo.setProductName(mcptProducTypeDto.getProductTypeName());
			// 查询这个用户手机号的归属地
			Map<String, Object> selectAttributionByMobileSix = loanInfoIDragonService
					.selectAttributionByMobileSix(user.getMobileNo().substring(0, 7));
			if (selectAttributionByMobileSix != null) {
				Object provinceObj = selectAttributionByMobileSix.get("province");
				Object cityObj = selectAttributionByMobileSix.get("city");
				if (provinceObj != null) {
					acLoanApplyInfo.setMobileAffiliationProvince(provinceObj.toString());
				}
				if (cityObj != null) {
					acLoanApplyInfo.setMobileAffiliationCity(cityObj.toString());
				}
			}
			MarvelsLogUtil.getInstance().info("5.ClientAppServiceImpl.applyLoan" + System.currentTimeMillis());

			//acLoanApplyInfo.setCreditLvl("A");
			acLoanApplyInfo.setChannelType("103");
			acLoanApplyInfo.setMobileNum(user.getMobileNo());
			acLoanApplyInfo.setAge(IdcardUtil.getAgeByIdCard(realNameAuthentication.getIdentityCardNo()));
			if(null != realNameAuthentication.getSex()) {
				acLoanApplyInfo.setSex(realNameAuthentication.getSex().toString());
			}
			acLoanApplyInfo.setBirthDate(DateUtil.parse(realNameAuthentication.getBirthday()));
			loanInfoIDragonService.input(acLoanApplyInfo);
			try {
				acApplyEnvironmentinfo.setLoanId(loanId);
				loanInfoIDragonService.insertAcApplyEnvironmentInfo(acApplyEnvironmentinfo);
			} catch (Exception e1) {
				MarvelsLogUtil.getInstance().error("存入环境信息异常", e1);
			}
			loanInfoIDragonService.updateLoanStatus(loanId, "K00",user.getRealName());

			resultMap = new HashMap<String, String>(2);
			resultMap.put("loanId", loanId);
			// 进件成功，添加新流程节点信息
			MarvelsLogUtil.getInstance().info("======进件成功，初始化新流程节点，参数:" + loanId);
			acLoanApplyNodeService.insertSelective(loanId, ApplyNode.APPLY_INIT);
		} catch (Exception e) {
			MarvelsLogUtil.getInstance().error("=====apply/loan=====", e);
			return FintechResult.getResult(ErrorCode.FAIL, "系统异常", null);
		}
		return FintechResult.getResult(ErrorCode.SUCCESS, "操作成功", resultMap);
	}

	/**
	 * 客户app第一次进件 立即申请<br>
	 * 只允许进件线上
	 * @param shortUrl
	 * @param response
	 * @return
	 */
	@Override
	public FintechResult applyReLoan(ProductApplyDTO productApplyDTO, AcApplyEnvironmentInfo acApplyEnvironmentinfo,String accessToken, String idFintechUmUser) {
		MarvelsLogUtil.getInstance().info("接受请求applyReLoan,进件参数:" + JSON.toJSONString(productApplyDTO) + ",环境信息:"
				+ JSON.toJSONString(acApplyEnvironmentinfo));

		Map<String, String> resultMap = null;
		User user = UserUtils.getUser(accessToken, idFintechUmUser);
		try {
			if (user == null) {
				return FintechResult.getResult(ReturnCode.tokenInvalid.getErrorCode(), "登录超时，请重新登录！", null);
			}
			//1.判断是否已经实名验证,如果没有则驳回
			RealNameAuthentication realNameAuthentication = realNameAuthenticationService.queryByUserId(user.getId());
			if (realNameAuthentication == null) {
				return FintechResult.getResult(ErrorCode.NO_VERIFY, "请先去实名验证", null);
			}

			//2.是否在本地黑名单
			String blackListVerifyNew = loanInfoIDragonService.blackListVerifyNew(realNameAuthentication.getIdentityCardNo(), user.getMobileNo());
			if (StrUtil.isNotEmpty(blackListVerifyNew)) {//如果在本地黑名单,则直接决策拒绝
				return FintechResult.getResult(ErrorCode.LIMIT_CALCULATE_DEFEATED, "您暂时不符合我们公司的申请条件", resultMap);
			}
			//从实名认证信息中获取身份证号码
			String identityCardNo = realNameAuthentication.getIdentityCardNo();

			//防止进件数据异常
			if(productApplyDTO.getApplyMoney() == null || productApplyDTO.getProductId() == null){
				return FintechResult.getResult(ErrorCode.FAIL, "系统正忙，请退出APP重试", null);
			}

//			String daysStr = FileDragonUtils.getValueByPropertiesKey("ref_max_apply_days");
//			MarvelsLogUtil.getInstance().info("ClientAppServiceImpl.applyReLoan daysStr" + daysStr);
//			int days = daysStr == null ? 30 : Integer.parseInt(daysStr);
//			boolean isPass = loanInfoIDragonService.isPassRule(realNameAuthentication.getIdentityCardNo(), days);
//			if(!isPass){
//				return FintechResult.getResult(ErrorCode.FAIL, "你暂时不符合申请条件，请" + days + "天后再次尝试申请", null);
//			}

			//5.是否存在贷款
			String applyingStatus = loanInfoIDragonService.selectCustApplyingStatus(identityCardNo);
			if (StrUtil.isNotEmpty(applyingStatus)) {
				applyingStatus = applyingStatus.trim();
				//5.1 判断是否处于已放款状态
				if ("D01".contains(applyingStatus)) {
					return FintechResult.getResult(ErrorCode.REPETITION_COMMIT_PAYED, "有正在还款中的贷款", null);
				}

				//5.2 判断是否是重复提交贷款申请
				if (Constant.LOAN_STATUS_APPLY.indexOf(applyingStatus) >= 0) {
					return FintechResult.getResult(ErrorCode.REPETITION_COMMIT, "重复提交贷款申请，请前往进度查询查看", null);
				}
				// 5.3 处于待放款状态
				return FintechResult.getResult(ErrorCode.REPETITION_COMMIT_PAYING, "有待放款申请", null);
			}

			//6.保存贷款信息
			String loanId = loanInfoIDragonService.generateLoanId();
			AcLoanApplyInfo acLoanApplyInfo = ProductApplyDTO.getAcLoanApplyInfo(productApplyDTO,
					realNameAuthentication);

			// 查询原本的进件信息
			AcLoanApplyInfo loan = loanInfoIDragonService.queryLoanBasicInfo(productApplyDTO.getReloanId());
			if (loan != null) {
				UserDataDTO userDataDTO = new UserDataDTO();
				userDataDTO.setLoanId(loanId);
				BeanUtils.copyProperties(loan, userDataDTO);
				BeanUtils.copyProperties(userDataDTO, acLoanApplyInfo, "loanId", "email");
				acLoanApplyInfo.setReceiveAcct(loan.getReceiveAcct());
				acLoanApplyInfo.setReceiveAcctName(loan.getReceiveAcctName());
				acLoanApplyInfo.setReceiveBankName(loan.getReceiveBankName());
				acLoanApplyInfo.setRepayAcct(loan.getRepayAcct());
				acLoanApplyInfo.setRepayAcctName(loan.getRepayAcctName());
				acLoanApplyInfo.setRepayBankName(loan.getRepayBankName());
			}
			if (StrUtil.isEmpty(acLoanApplyInfo.getUsedName())) {
				acLoanApplyInfo.setUsedName("消费");
			}
			acLoanApplyInfo.setLoanId(loanId);
			// 插入此次进件
			// 查询这个用户手机号的归属地
			Map<String, Object> selectAttributionByMobileSix = loanInfoIDragonService
					.selectAttributionByMobileSix(user.getMobileNo().substring(0, 7));
			if (selectAttributionByMobileSix != null) {
				Object provinceObj = selectAttributionByMobileSix.get("province");
				Object cityObj = selectAttributionByMobileSix.get("city");
				if (provinceObj != null) {
					acLoanApplyInfo.setMobileAffiliationProvince(provinceObj.toString());
				}
				if (cityObj != null) {
					acLoanApplyInfo.setMobileAffiliationCity(cityObj.toString());
				}
			}

			acLoanApplyInfo.setChannelType("103");
			acLoanApplyInfo.setMobileNum(user.getMobileNo());
			loanInfoIDragonService.input(acLoanApplyInfo);
			// 在这里加上所谓的什么鬼环境信息
//			try {
//				acApplyEnvironmentinfo.setLoanId(loanId);
//				loanInfoIDragonService.insertAcApplyEnvironmentInfo(acApplyEnvironmentinfo);
//			} catch (Exception e1) {
//				MarvelsLogUtil.getInstance().error("维护环境信息出错", e1);
//			}
			loanInfoIDragonService.updateLoanStatus(loanId, "K00",user.getRealName());

			// 进件成功，添加新流程节点信息
			MarvelsLogUtil.getInstance().info("======进件成功，初始化新流程节点，参数:" + loanId);
			acLoanApplyNodeService.insertSelective(loanId, ApplyNode.APPLY_INIT);
			acLoanApplyNodeService.insertSelective(loanId, ApplyNode.BIND_CARD);
			acLoanApplyNodeService.insertSelective(loanId, ApplyNode.LINKMAN_AUTH);
			acLoanApplyNodeService.insertSelective(loanId, ApplyNode.CARRIER_AUTH);
			if(acLoanApplyNodeService.isGoAlipay()){
				acLoanApplyNodeService.insertSelective(loanId, ApplyNode.ALIPAY_AUTH);
			}
			acLoanApplyNodeService.insertSelective(loanId, ApplyNode.REVIEW_DOING);

			// 写进件扩展表数据
			MarvelsLogUtil.getInstance().info("======进件成功，将复贷信息初始化到进件扩展表，参数:" + loanId);
			Map<String, Object> map = new HashMap<>();
			map.put("reloan_flag", "1");
			map.put("reloan_id", productApplyDTO.getReloanId());
			acLoanApplyInfoExtDragonService.operateExtColumn(loanId, map);

			// 发送到新核心
			asyncCallApi.sendLoanApplyMessage(loanId);
			AcLoanApplyInfo acLoanApplyInfoNew = new AcLoanApplyInfo();
			acLoanApplyInfoNew.setLoanId(loanId);
			acLoanApplyInfoNew.setGoNewMarvels(new Byte("1"));
			loanInfoIDragonService.input(acLoanApplyInfoNew);
	        MarvelsLogUtil.getInstance().info("=====复贷时将数据推送给新核心,loanId=" + loanId);

//			try {
//				EdcSharedDataDTO  dataDTO=new EdcSharedDataDTO();
//				dataDTO.setCreatedBy("system");
//				dataDTO.setCreatedDate(new Date());
//				dataDTO.setCustName(realNameAuthentication.getRealName());
//				dataDTO.setCustCardNo(realNameAuthentication.getIdentityCardNo());
//				dataDTO.setLoanId(loanId);
//				dataDTO.setMobileNo(user.getMobileNo());
//				dataDTO.setStatus("2");//申请
//				dataDTO.setSrc(loanId.substring(0, 3));
//				dataDTO.setUpdatedDate(new Date());
//				dataDTO.setUpdatedBy("system");
//				sharedDataMqProvideApi.synSharedDataUpdate(dataDTO);
//			} catch (Exception e) {
//				MarvelsLogUtil.getInstance().error(">>>>>>loanId"+loanId+"进件申请推送共享数据失败:",e);
//			}

			resultMap = new HashMap<String, String>(2);
			resultMap.put("loanId", loanId);
			MarvelsLogUtil.getInstance().info("-----------apply/loan------e------------" + productApplyDTO.toString());
		} catch (Exception e) {
			MarvelsLogUtil.getInstance().error("=====apply/loan=====", e);
			MarvelsLogUtil.getInstance().info("-----------apply/loan------error------------" + productApplyDTO.toString());
			return FintechResult.getResult(ErrorCode.FAIL, "系统异常", null);
		}
		return FintechResult.getResult(ErrorCode.SUCCESS, "操作成功", resultMap);
	}

	/**
	 * 客户app第一次进件 立即申请<br>
	 * 只允许进件线上
	 * @param shortUrl
	 * @param response
	 * @return
	 */
	@Override
	public FintechResult applyV2ReLoan(ProductApplyDTO productApplyDTO, AcApplyEnvironmentInfo acApplyEnvironmentinfo,String accessToken, String idFintechUmUser) {
		MarvelsLogUtil.getInstance().info("v2接受请求applyReLoan,进件参数:" + JSON.toJSONString(productApplyDTO) + ",环境信息:"
				+ JSON.toJSONString(acApplyEnvironmentinfo));

		Map<String, String> resultMap = null;
		User user = UserUtils.getUser(accessToken, idFintechUmUser);
		try {
			if (user == null) {
				return FintechResult.getResult(ReturnCode.tokenInvalid.getErrorCode(), "登录超时，请重新登录！", null);
			}
			//1.判断是否已经实名验证,如果没有则驳回
			RealNameAuthentication realNameAuthentication = realNameAuthenticationService.queryByUserId(user.getId());
			if (realNameAuthentication == null) {
				return FintechResult.getResult(ErrorCode.NO_VERIFY, "请先去实名验证", null);
			}

			//2.是否在本地黑名单
			String blackListVerifyNew = loanInfoIDragonService.blackListVerifyNew(realNameAuthentication.getIdentityCardNo(), user.getMobileNo());
			if (StrUtil.isNotEmpty(blackListVerifyNew)) {//如果在本地黑名单,则直接决策拒绝
				return FintechResult.getResult(ErrorCode.LIMIT_CALCULATE_DEFEATED, "您暂时不符合我们公司的申请条件", resultMap);
			}
			//从实名认证信息中获取身份证号码
			String identityCardNo = realNameAuthentication.getIdentityCardNo();

			//防止进件数据异常
			if(productApplyDTO.getApplyMoney() == null || productApplyDTO.getProductId() == null){
				return FintechResult.getResult(ErrorCode.FAIL, "系统正忙，请退出APP重试", null);
			}

			String daysStr = FileDragonUtils.getValueByPropertiesKey("ref_max_apply_days");
			MarvelsLogUtil.getInstance().info("v2 ClientAppServiceImpl.applyReLoan daysStr" + daysStr);
			int days = daysStr == null ? 30 : Integer.parseInt(daysStr);
			boolean isPass = loanInfoIDragonService.isPassRule(realNameAuthentication.getIdentityCardNo(), days);
			if(!isPass){
				return FintechResult.getResult(ErrorCode.FAIL, "你暂时不符合申请条件，请" + days + "天后再次尝试申请", null);
			}

			//5.是否存在贷款
			String applyingStatus = loanInfoIDragonService.selectCustApplyingStatus(identityCardNo);
			if (StrUtil.isNotEmpty(applyingStatus)) {
				applyingStatus = applyingStatus.trim();
				//5.1 判断是否处于已放款状态
				if ("D01".contains(applyingStatus)) {
					return FintechResult.getResult(ErrorCode.REPETITION_COMMIT_PAYED, "有正在还款中的贷款", null);
				}

				//5.2 判断是否是重复提交贷款申请
				if (Constant.LOAN_STATUS_APPLY.indexOf(applyingStatus) >= 0) {
					return FintechResult.getResult(ErrorCode.REPETITION_COMMIT, "重复提交贷款申请，请前往进度查询查看", null);
				}
				// 5.3 处于待放款状态
				return FintechResult.getResult(ErrorCode.REPETITION_COMMIT_PAYING, "有待放款申请", null);
			}

			//6.保存贷款信息
			String loanId = loanInfoIDragonService.generateLoanId();
			AcLoanApplyInfo acLoanApplyInfo = ProductApplyDTO.getAcLoanApplyInfo(productApplyDTO,
					realNameAuthentication);

			// 查询原本的进件信息
			AcLoanApplyInfo loan = loanInfoIDragonService.queryLoanBasicInfo(productApplyDTO.getReloanId());
			if (loan != null) {
				UserDataDTO userDataDTO = new UserDataDTO();
				userDataDTO.setLoanId(loanId);
				BeanUtils.copyProperties(loan, userDataDTO);
				BeanUtils.copyProperties(userDataDTO, acLoanApplyInfo, "loanId", "email");
				acLoanApplyInfo.setReceiveAcct(loan.getReceiveAcct());
				acLoanApplyInfo.setReceiveAcctName(loan.getReceiveAcctName());
				acLoanApplyInfo.setReceiveBankName(loan.getReceiveBankName());
				acLoanApplyInfo.setRepayAcct(loan.getRepayAcct());
				acLoanApplyInfo.setRepayAcctName(loan.getRepayAcctName());
				acLoanApplyInfo.setRepayBankName(loan.getRepayBankName());
			}
			if (StrUtil.isEmpty(acLoanApplyInfo.getUsedName())) {
				acLoanApplyInfo.setUsedName("消费");
			}
			acLoanApplyInfo.setLoanId(loanId);
			// 插入此次进件
			// 查询这个用户手机号的归属地
			Map<String, Object> selectAttributionByMobileSix = loanInfoIDragonService
					.selectAttributionByMobileSix(user.getMobileNo().substring(0, 7));
			if (selectAttributionByMobileSix != null) {
				Object provinceObj = selectAttributionByMobileSix.get("province");
				Object cityObj = selectAttributionByMobileSix.get("city");
				if (provinceObj != null) {
					acLoanApplyInfo.setMobileAffiliationProvince(provinceObj.toString());
				}
				if (cityObj != null) {
					acLoanApplyInfo.setMobileAffiliationCity(cityObj.toString());
				}
			}

			acLoanApplyInfo.setChannelType("103");
			acLoanApplyInfo.setMobileNum(user.getMobileNo());
			if ("XXSCH5".equals(productApplyDTO.getSource())) {
				acLoanApplyInfo.setSource("XXSCH5");
			}
			loanInfoIDragonService.input(acLoanApplyInfo);
			// 在这里加上所谓的什么鬼环境信息
			try {
				acApplyEnvironmentinfo.setLoanId(loanId);
				loanInfoIDragonService.insertAcApplyEnvironmentInfo(acApplyEnvironmentinfo);
			} catch (Exception e1) {
				MarvelsLogUtil.getInstance().error("v2维护环境信息出错", e1);
			}
			loanInfoIDragonService.updateLoanStatus(loanId, "K00",user.getRealName());

			// 进件成功，添加新流程节点信息
			MarvelsLogUtil.getInstance().info("======v2进件成功，初始化新流程节点，参数:" + loanId);
			acLoanApplyNodeService.insertSelective(loanId, ApplyNode.APPLY_INIT);
			//acLoanApplyNodeService.insertSelective(loanId, ApplyNode.BIND_CARD);

			// 写进件扩展表数据
			MarvelsLogUtil.getInstance().info("======v2进件成功，将复贷信息初始化到进件扩展表，参数:" + loanId);
			Map<String, Object> map = new HashMap<>();
			map.put("reloan_flag", "1");
			map.put("reloan_id", productApplyDTO.getReloanId());
			acLoanApplyInfoExtDragonService.operateExtColumn(loanId, map);

			resultMap = new HashMap<String, String>(2);
			resultMap.put("loanId", loanId);
			MarvelsLogUtil.getInstance().info("-----------v2 apply/loan------e------------" + productApplyDTO.toString());
		} catch (Exception e) {
			MarvelsLogUtil.getInstance().error("=====v2 apply/loan=====", e);
			MarvelsLogUtil.getInstance().info("-----------v2 apply/loan------error------------" + productApplyDTO.toString());
			return FintechResult.getResult(ErrorCode.FAIL, "系统异常", null);
		}
		return FintechResult.getResult(ErrorCode.SUCCESS, "操作成功", resultMap);
	}

	/**
	 * 本地黑名单验证
	 *
	 * @param mobileSet
	 * @return false.正常，true.黑名单
	 */
	@SuppressWarnings("unchecked")
	private boolean verifyLocalMobileBlack(Set<String> mobileSet) {
		MarvelsLogUtil.getInstance().info("========进入本地黑名单校验set:" + com.alibaba.fastjson.JSONObject.toJSONString(mobileSet));
		// 兼容整合后因为redis反序列化问题
		String setStr = null;
		try {
			setStr = RedisUtils.getInstance().get("blackData");
		} catch (Exception e) {
			RedisUtils.getInstance().del("blackData");
		}
		HashSet<String> blackSet = null;
		if (StrUtil.isEmpty(setStr)) {
			blackSet = blackInfoIDragonService.getAllMobile();
			RedisUtils.getInstance().setex("blackData",
					60 * 60 * Integer.parseInt(FileDragonUtils.getValueByPropertiesKey("blackData_time")),
					com.alibaba.fastjson.JSONObject.toJSONString(blackSet));
		} else {
			blackSet = (HashSet<String>) com.alibaba.fastjson.JSONObject.parseObject(setStr, HashSet.class);
		}
		MarvelsLogUtil.getInstance().info("========本地黑名单Data,set:" + com.alibaba.fastjson.JSONObject.toJSONString(blackSet));
		if (null != blackSet && blackSet.size() > 0) {
			blackSet.retainAll(mobileSet);
			if (blackSet.size() > 0) {
				return true;
			}
		}
		return false;
	}



	@Override
	public FintechResult queryProductType() {
		MarvelsLogUtil.getInstance().info("======查询当前产品");
		try {
			Map<String, Object> rtnMap = productTypeService.getHomeInfo();
			if (rtnMap == null) {
				MarvelsLogUtil.getInstance().info("======未配置线上产品");
				return FintechResult.getFailResult(ReturnCode.fail.getErrorCode(), "未配置产品");
			}
			MarvelsLogUtil.getInstance().info("======查询当前线上产品成功");
			rtnMap.put("isGoAlipay", acLoanApplyNodeService.isGoAlipay());
			String channel = ServerProperties.getValue(configPropertiesPath, "common.properties", "payment_channel");
			rtnMap.put("quickRepayment", false);
			if(PayContants.PAY_CHANNEL_HJ.getCode().equals(channel)){
				rtnMap.put("quickRepayment", true);
			}
			return FintechResult.getSuccessResult(rtnMap);
		} catch (Exception e) {
			MarvelsLogUtil.getInstance().error("查询当前线上产品异常", e);
			return FintechResult.getFailResult(ReturnCode.fail.getErrorCode(), "查询当前线上产品异常");
		}
	}

	@Override
	public FintechResult queryLastApplyNode(int userId) {
		MarvelsLogUtil.getInstance().info("======查询最新的节点信息，userId=[" + userId + "]");
		try {
			// 查询用户当前在途的单
			RealNameAuthentication realNameAuthentication = realNameAuthenticationService.queryByUserId(userId);
			if(null == realNameAuthentication || StringUtils.isBlank(realNameAuthentication.getIdentityCardNo())) {
				MarvelsLogUtil.getInstance().info("======不存在在途的单");
				return FintechResult.getSuccessResult(null);
			}

			String loanId = loanInfoIDragonService.selectCustApplyingLoanId(realNameAuthentication.getIdentityCardNo());
			if (StrUtil.isEmpty(loanId)) {
				MarvelsLogUtil.getInstance().info("======不存在在途的单");
				return FintechResult.getSuccessResult(null);
			}
			// 查询节点信息
			AcLoanApplyNode applyNode = acLoanApplyNodeService.queryLastApplyNode(loanId);
			MarvelsLogUtil.getInstance().info("======查询最新的节点信息结果:" + applyNode);
			if (applyNode == null) {
				return FintechResult.getFailResult(ReturnCode.fail.getErrorCode(), "查询最新的节点信息为空");
			}

			// 查询进件信息
			AcLoanApplyInfo acLoanApplyInfo = loanInfoIDragonService.queryLoanBasicInfo(loanId);
			applyNode.setAcLoanApplyInfo(acLoanApplyInfo);
			MarvelsLogUtil.getInstance().info("======查询最新的节点信息成功，applyNode=" + applyNode);
			return FintechResult.getSuccessResult(applyNode);
		} catch (Exception e) {
			MarvelsLogUtil.getInstance().error("查询最新的节点信息异常", e);
			return FintechResult.getFailResult(ReturnCode.fail.getErrorCode(), "查询最新的节点信息异常");
		}
	}

	@Override
	public FintechResult queryAllApplyeList(int userId,String loanStatus) {
		MarvelsLogUtil.getInstance().info("======查询用户所有申请信息，[userId=" + userId + "][loanStatus="+loanStatus+"]");
		try {
			// 查询用户当前在途的单
			RealNameAuthentication realNameAuthentication = realNameAuthenticationService.queryByUserId(userId);
			if(null == realNameAuthentication || StringUtils.isBlank(realNameAuthentication.getIdentityCardNo())) {
				MarvelsLogUtil.getInstance().info("======不存在在途的单");
				return FintechResult.getSuccessResult(null);
			}
			List<Order> orderList = new ArrayList<Order>();
			PageBounds pageBounds = new PageBounds(1, 1000, orderList);
			Map<String,Object> paramMap = new HashMap<String,Object>();
			paramMap.put("custIdCard",realNameAuthentication.getIdentityCardNo());
			paramMap.put("loanStatus", loanStatus);
			List<AcLoanApplyInfo> resultList = acLoanApplyInfoRepository.queryLoanInfoByCondition(paramMap, pageBounds);
			if (CollectionUtils.isEmpty(resultList)) {
				MarvelsLogUtil.getInstance().info("======不存在在途的单");
				return FintechResult.getSuccessResult(null);
			}

			List<AcLoanApplyNode> applyNodeList = new ArrayList<>();

			for (AcLoanApplyInfo acLoanApplyInfo : resultList) {
				// 查询节点信息
				AcLoanApplyNode applyNode = acLoanApplyNodeService.queryLastApplyNode(acLoanApplyInfo.getLoanId());
				MarvelsLogUtil.getInstance().info("======queryAllApplyeList查询最新的节点信息结果:" + applyNode);
				MarvelsLogUtil.getInstance().info("======queryAllApplyeList.applyNode日期格式化:" + DateUtil.format(applyNode.getCreatedDate(),"yyyy-MM-dd HH:mm:ss"));
				MarvelsLogUtil.getInstance().info("======queryAllApplyeList.acLoanApplyInfo日期格式化:" + DateUtil.format(acLoanApplyInfo.getUpdateTime(),"yyyy-MM-dd HH:mm:ss"));
				if (applyNode != null) {
					applyNode.setAcLoanApplyInfo(acLoanApplyInfo);
					applyNodeList.add(applyNode);
				}
			}
			return FintechResult.getSuccessResult(applyNodeList);
		} catch (Exception e) {
			MarvelsLogUtil.getInstance().error("查询最新的节点信息异常", e);
			return FintechResult.getFailResult(ReturnCode.fail.getErrorCode(), "查询最新的节点信息异常");
		}
	}

	@Override
	public FintechResult callBackMxTask(Map<String, String> map) {
//		MarvelsLogUtil.getInstance().info("======魔蝎TASKID回调，参数:" + JSON.toJSONString(map));
//		try {
//			if (map == null) {
//				return FintechResult.getFailResult(ReturnCode.fail.getErrorCode(), "回调参数为空");
//			}
//			long time1 = System.currentTimeMillis();
//			MoxieResponse response = MoXie.createMoxieTask(map);
//			MarvelsLogUtil.getInstance().info("======魔蝎任务表入库结果:" + response);
//			if (response == null || response.getCode() != 0) {
//				return FintechResult.getFailResult(ReturnCode.fail.getErrorCode(), "魔蝎任务表入库失败");
//			}
//			long time2 = System.currentTimeMillis();
//			MarvelsLogUtil.getInstance().info("##################魔蝎任务表入库耗时统计:" + (time2 - time1));
//			// 2018/12/17 修改为异步获取数据
//			if (StrUtil.equals(MoXieTaskType.CARRIER.getType() + "", map.get("type"))) {
//				// 扭转节点
//				acLoanApplyNodeService.insertSelective(map.get("loanId"), ApplyNode.CARRIER_AUTH);
//				try {
//					MoXieTaskResult moXieTaskResult = MoXie.runMoXieCarrierTask(map.get("taskId"), map.get("loanId"));
//					//更改运营商认证结果
//					Map<String, Object> operatorAuth = new HashMap<String, Object>();
//					operatorAuth.put("operator_auth", moXieTaskResult.isResult() ? "1" : null);
//					boolean operateResult = acLoanApplyInfoExtDragonService.operateExtColumn(map.get("loanId"), operatorAuth);
//					MarvelsLogUtil.getInstance().info("运营商认证结果写入，loanId：" + map.get("loanId") + ",结果：" + operateResult);
//
//				} catch (Exception e) {
//					MarvelsLogUtil.getInstance().error("同步运营商认证结果写入异常，loanId：" + map.get("loanId"), e);
//				}
//				return FintechResult.getSuccessResult(null);
//			}
//			if (StrUtil.equals(MoXieTaskType.ALIPAY.getType() + "", map.get("type"))) {
//				if(acLoanApplyNodeService.isGoAlipay()){
//					// 扭转节点
//					acLoanApplyNodeService.insertSelective(map.get("loanId"), ApplyNode.ALIPAY_AUTH);
//					try {
//						MoXieTaskResult moXieTaskResult = MoXie.runMoXieAlipayTask(map.get("taskId"), map.get("loanId"));
//						if (moXieTaskResult.isResult()) {
//							//记录支付宝芝麻分结果
//							Map<String, Object> alipayAuth = new HashMap<String, Object>();
//							alipayAuth.put("zms_core", moXieTaskResult.getZmsCore());
//							alipayAuth.put("huabai_limit", moXieTaskResult.getHuabaiLimit());
//							alipayAuth.put("alipay_auth", "1");
//							boolean result = acLoanApplyInfoExtDragonService.operateExtColumn(map.get("loanId"), alipayAuth);
//							MarvelsLogUtil.getInstance().info("支付宝芝麻分结果写入，loanId：" + map.get("loanId") + ",结果：" + result);
//						}
//					} catch (Exception e) {
//						MarvelsLogUtil.getInstance().error("支付宝芝麻分结果写入异常，loanId：" + map.get("loanId"), e);
//					}
//				}
//				return FintechResult.getSuccessResult(null);
//			}
//			long time3 = System.currentTimeMillis();
//			MarvelsLogUtil.getInstance().info("##################查询运营商数据耗时统计:" + (time3 - time2));
//			MarvelsLogUtil.getInstance().info("======魔蝎TASKID回调成功");
//			return FintechResult.getFailResult(ReturnCode.fail.getErrorCode(), "魔蝎数据类型不正确");
//		} catch (Exception e) {
//			MarvelsLogUtil.getInstance().error("魔蝎TASKID回调异常", e);
//			return FintechResult.getFailResult(ReturnCode.fail.getErrorCode(), "魔蝎TASKID回调异常");
//		}
		return FintechResult.getSuccessResult(null);
	}

	/**
	 * 定时拉取魔蝎数据
	 */
	// @Scheduled(cron = "0 */1 * * * ?")
	public void runGetMoXieDataTask(){
//
//		MarvelsLogUtil.getInstance().info("======魔蝎拉取运营商数据定时任务开始  start");
//		try {
//			// 如果处理中停留超过15分钟，就将该单自动重新转为未处理
//			MoXie.updateMoxieProcessing();
//			List<MoxieTaskInfo> moxieTaskList = MoXie.selectMoxieTaskInfo(String.valueOf(MoXieTaskType.CARRIER.getType()));
//			for (MoxieTaskInfo moxieTaskInfo : moxieTaskList) {
//				try {
//					MarvelsLogUtil.getInstance().info("runMoXieCarrierTask 运营商 loanId：" + moxieTaskInfo.getLoanId() + ",taskId：" + moxieTaskInfo.getTaskId());
//					MoXieTaskResult moXieTaskResult = MoXie.runMoXieCarrierTask(moxieTaskInfo.getTaskId(), moxieTaskInfo.getLoanId());
//					//更改运营商认证结果
//					Map<String, Object> operatorAuth = new HashMap<String, Object>();
//					operatorAuth.put("operator_auth", moXieTaskResult.isResult() ? "1" : null);
//					boolean operateResult = acLoanApplyInfoExtDragonService.operateExtColumn(moxieTaskInfo.getLoanId(), operatorAuth);
//					MarvelsLogUtil.getInstance().info("运营商认证结果写入，loanId：" + moxieTaskInfo.getLoanId() + ",结果：" + operateResult);
//				}
//				catch (Exception e) {
//					MarvelsLogUtil.getInstance().error("runMoXieCarrierTask 运营商 异常，loanId：" + moxieTaskInfo.getLoanId(), e);
//				}
//			}
//		} catch (Exception e) {
//			MarvelsLogUtil.getInstance().error("======魔蝎拉取运营商数据定时任务异常  error", e);
//		}
//		MarvelsLogUtil.getInstance().info("======魔蝎拉取运营商数据定时任务结束  end");
//
//
//		MarvelsLogUtil.getInstance().info("======魔蝎拉取支付宝数据定时任务开始  start");
//		try {
//			List<MoxieTaskInfo> moxieTaskList = MoXie.selectMoxieTaskInfo(String.valueOf(MoXieTaskType.ALIPAY.getType()));
//			for (MoxieTaskInfo moxieTaskInfo : moxieTaskList) {
//				try {
//					MarvelsLogUtil.getInstance().info("runMoXieCarrierTask 支付宝 loanId：" + moxieTaskInfo.getLoanId() + ",taskId：" + moxieTaskInfo.getTaskId());
//					MoXieTaskResult moXieTaskResult = MoXie.runMoXieAlipayTask(moxieTaskInfo.getTaskId(), moxieTaskInfo.getLoanId());
//					if (moXieTaskResult.isResult()) {
//						//记录支付宝芝麻分结果
//						Map<String, Object> alipayAuth = new HashMap<String, Object>();
//						alipayAuth.put("zms_core", moXieTaskResult.getZmsCore());
//						alipayAuth.put("huabai_limit", moXieTaskResult.getHuabaiLimit());
//						alipayAuth.put("alipay_auth", "1");
//						boolean result = acLoanApplyInfoExtDragonService.operateExtColumn(moxieTaskInfo.getLoanId(), alipayAuth);
//						MarvelsLogUtil.getInstance().info("支付宝芝麻分结果写入，loanId：" + moxieTaskInfo.getLoanId() + ",结果：" + result);
//					}
//				}
//				catch (Exception e) {
//					MarvelsLogUtil.getInstance().error("runMoXieCarrierTask 支付宝异常，loanId：" + moxieTaskInfo.getLoanId(), e);
//				}
//			}
//		} catch (Exception e) {
//			MarvelsLogUtil.getInstance().error("======魔蝎拉取支付宝数据定时任务异常  error", e);
//		}
//		MarvelsLogUtil.getInstance().info("======魔蝎拉取支付宝数据定时任务结束  end");
	}


	@Override
	public FintechResult queryLoanApplyInfo(String loanId) {
		MarvelsLogUtil.getInstance().info("======确认贷款详情信息，参数:" + loanId);
		try {
			if (StrUtil.isEmpty(loanId)) {
				return FintechResult.getFailResult(ReturnCode.fail.getErrorCode(), "贷款编号为空");
			}
			AcLoanApplyInfo loanInfo = loanInfoIDragonService.queryLoanBasicInfo(loanId);
			if (loanInfo == null) {
				return FintechResult.getFailResult(ReturnCode.fail.getErrorCode(), "申请信息不存在");
			}
//
//			String productType = loanInfo.getProductType();
//			loanInfo.getProductId();
//			/*Map<String, Object> reqMap = new HashMap<String, Object>();
//			reqMap.put("productType", productType);
//			JsonResult<Map> jsonResult = newMarvelCoreService.getForObjectPost(MarvelURLConstant.PRODUCT_API_SERVICE_FEECODE, reqMap, Map.class);
//			Map data = jsonResult.getData();*/
//
//			com.marvels.product.productmanage.dto.McptProductDto paramDto = new com.marvels.product.productmanage.dto.McptProductDto();
//			paramDto.setProductType(productType);
//			// 调用返回数据
//			Map data = productTypeService.queryByConsultingFeeCode(paramDto);
//			// 返回数据
//			Map<String, Object> retMap = new HashMap<String, Object>();
//			if(null != data){
//				BigDecimal consultingFeePercentage = (BigDecimal)data.get("percentage");
//				BigDecimal manageFeePercentage = (BigDecimal)data.get("manageFeePercentage");
//				// 生成返回数据所需的字段
//				BigDecimal loanMoneyAct = loanInfo.getLoanMoneyAct();// 应还金额
//				Date applyTime = loanInfo.getApplyTime();// 申请时间
//				Date clearDateAct = loanInfo.getClearDateAct();// 约定还款日
//
//				if(manageFeePercentage == null) {
//					manageFeePercentage = BigDecimal.ZERO;
//				}
//				//管理费
//				BigDecimal manageFee = loanMoneyAct.multiply(manageFeePercentage);
//
//				if(manageFeePercentage == null) {
//					manageFeePercentage = BigDecimal.ZERO;
//				}
//				//咨询费
//				BigDecimal consultingFee = loanMoneyAct.multiply(consultingFeePercentage);
//				//到手金额=核批金额-咨询费
//				BigDecimal arrivalAmount = loanMoneyAct.subtract(consultingFee);
//				//应还款总金额
//				BigDecimal repaymentAmount = loanMoneyAct.add(consultingFee).add(manageFee);
//				// 借款天数
//				Integer applyTerms = loanInfo.getApplyTerms();
//				String cycle = data.get("cycle") == null ? "" : (String) data.get("cycle");
//				Integer cycleDay = 0;
//				if(StrUtil.isNotEmpty(cycle)){
//					if("A000".equals(cycle)){
//						cycleDay = 1;
//					}else if("A001".equals(cycle)){
//						if(StringUtils.equalsIgnoreCase("Y", CommonProperties.getNewRepaymentFlag())) {
//							cycleDay = 8;
//						}else {
//							cycleDay = 7;
//						}
//					}else if("A002".equals(cycle)){
//						cycleDay = 14;
//					}else if("A003".equals(cycle)){
//						cycleDay = 15;
//					}else if("A004".equals(cycle)){
//						cycleDay = 30;
//					}else if("A005".equals(cycle)){
//						cycleDay = 90;
//					}
//				}
//				if(null != applyTerms){
//					applyTerms = applyTerms * cycleDay;
//				}
//				BigDecimal coverCharge = BigDecimal.ZERO;
//				if(StringUtils.equalsIgnoreCase("Y", CommonProperties.getNewRepaymentFlag())) {
//					coverCharge = manageFee;
//					clearDateAct = DateUtils.addDays(Calendar.getInstance().getTime(), 1);
//				}else {
//					coverCharge = consultingFee;
//				}
//				retMap.put("loanId", loanId);//贷款编号
//				retMap.put("loanMoneyAct", loanMoneyAct);//应还本金
//				retMap.put("repaymentAmount", repaymentAmount);//应还总金额
//				retMap.put("arrivalAmount", arrivalAmount);//到账金额
//				retMap.put("coverCharge", coverCharge);//app使用到的服务费
//				retMap.put("manageFee", manageFee);//管理费
//				retMap.put("consultingFee", consultingFee);//咨询费
//				retMap.put("borDays", applyTerms);//借款天数
//				retMap.put("applyTime", applyTime);//申请时间
//
//				if(null == clearDateAct){
//					clearDateAct = DateUtils.addDays(Calendar.getInstance().getTime(), (applyTerms.intValue()-1));
//				}
			Map<String, Object> retMap = new HashMap<String, Object>();
			retMap.put("acLoanApplyInfo", loanInfo);//基本信息
//			}

			MarvelsLogUtil.getInstance().info("======查询贷款详情信息结果:" + JSON.toJSONString(retMap));
			MarvelsLogUtil.getInstance().info("======查询贷款详情信息成功");
			return FintechResult.getSuccessResult(retMap);
		} catch (Exception e) {
			MarvelsLogUtil.getInstance().error("确认贷款详情信息异常,loanId=[" + loanId + "]", e);
			return FintechResult.getFailResult(ReturnCode.fail.getErrorCode(), "确认贷款详情信息异常");
		}
	}

	@SuppressWarnings("unchecked")
	@Override
	public FintechResult confirmLoanApply(String loanId,User user) {
		MarvelsLogUtil.getInstance().info("======确认贷款申请，参数:" + loanId);
		try {
			if (StrUtil.isEmpty(loanId)) {
				return FintechResult.getFailResult(ReturnCode.fail.getErrorCode(), "贷款编号为空");
			}
			// 判断当前节点是否审核通过
			AcLoanApplyNode applyNode = acLoanApplyNodeService.queryLastApplyNode(loanId);
			if (applyNode == null) {
				return FintechResult.getFailResult(ReturnCode.fail.getErrorCode(), "查询最新的节点信息为空");
			}
			if (applyNode.getNodeCode() != ApplyNode.REVIEW_SUCCESS.getCode()) {
				return FintechResult.getFailResult(ReturnCode.fail.getErrorCode(), "只有审核通过的申请才能确认借款操作");
			}

			// 判断是否完成绑卡
//			FintechResult fintechResult = confirmLoanDataFull(loanId);
//			MarvelsLogUtil.getInstance().info("判断是否完成绑卡:" + JSON.toJSONString(fintechResult));
//			if (fintechResult == null || !ReturnCode.success.getErrorCode().equals(fintechResult.getErrorCode())) {
//				return FintechResult.getFailResult(ReturnCode.fail.getErrorCode(), "确认贷款数据验证失败");
//			}
//			Map<String, String> map = (Map<String, String>) fintechResult.getData();
//			if (!"1".equals(map.get("bindCardFlag"))) {
//				return FintechResult.getFailResult(ReturnCode.fail.getErrorCode(), "未绑卡");
//			}
			loanInfoIDragonService.updateLoanStatus(loanId, "P05",user.getRealName());

			// 流程新流程节点（贷款确认）
			acLoanApplyNodeService.insertSelective(loanId, ApplyNode.LOAN_CONFIRM);
			MarvelsLogUtil.getInstance().info("======确认贷款申请成功");
			return FintechResult.getSuccessResult(null);
		} catch (Exception e) {
			MarvelsLogUtil.getInstance().error("确认贷款申请异常,loanId=[" + loanId + "]", e);
			return FintechResult.getFailResult(ReturnCode.fail.getErrorCode(), "确认贷款申请异常");
		}
	}

	@Override
	public FintechResult confirmLoanDataFull(String loanId) {
		MarvelsLogUtil.getInstance().info("======确认贷款数据是否完整（绑卡），参数:" + loanId);
		Map<String, String> rtnMap = new HashMap<>();
		try {
			if (StrUtil.isEmpty(loanId)) {
				return FintechResult.getFailResult(ReturnCode.fail.getErrorCode(), "贷款编号为空");
			}
			// 判断是否绑卡
			AcLoanApplyInfo loanInfo = loanInfoIDragonService.queryLoanBasicInfo(loanId);
			MarvelsLogUtil.getInstance().info("======查询进件信息结果:" + JSON.toJSONString(loanInfo));
			if (loanInfo == null) {
				return FintechResult.getFailResult(ReturnCode.fail.getErrorCode(), "进件信息为空");
			}
			if (StrUtil.isNotEmpty(loanInfo.getReceiveAcct())
					&& StrUtil.isNotEmpty(loanInfo.getReceiveAcctName())
					&& StrUtil.isNotEmpty(loanInfo.getReceiveBankName())) {
				// 已绑定卡
				rtnMap.put("bindCardFlag", "1");
			}

			// 判断是否签合同（通过附件表判断）
//			List<CmAttachment> queryAttachments = cmAttachmentService.queryAttachments(loanId,
//					"Q_MQ");
//			if (Collections3.isNotEmpty(queryAttachments) && !"0".equals(loanInfo.getIsSignCreditAuth())) {
//				// 已签署合同
//				rtnMap.put("contractFlag", "1");
//			}
			MarvelsLogUtil.getInstance().info("======确认贷款数据是否完整（绑卡）成功,rtnMap=" + JSON.toJSONString(rtnMap));
			return FintechResult.getSuccessResult(rtnMap);
		} catch (Exception e) {
			MarvelsLogUtil.getInstance().error("确认贷款数据是否完整异常,loanId=[" + loanId + "]", e);
			return FintechResult.getFailResult(ReturnCode.fail.getErrorCode(), "确认贷款数据是否完整异常");
		}
	}

	@Override
	public FintechResult addLinkManAuthNode(String loanId) {
		MarvelsLogUtil.getInstance().info("======添加通讯录认证成功节点流程信息，参数:" + loanId);
		AcLoanApplyNode applyNode = acLoanApplyNodeService.queryLastApplyNode(loanId);
		if (applyNode == null) {
			return FintechResult.getFailResult(ReturnCode.fail.getErrorCode(), "查询最新的节点信息为空");
		}

		AcLoanApplyNode acLoanApplyNode = new AcLoanApplyNode();
		acLoanApplyNode.setLoanId(loanId);
		acLoanApplyNode.setNodeCode(ApplyNode.LINKMAN_AUTH.getCode());
		acLoanApplyNode.setNodeMsg(ApplyNode.LINKMAN_AUTH.getMsg());
		return addLoanApplyNode(acLoanApplyNode);
	}


	@Override
	public FintechResult addLinkManAuthNodeV2(String loanId, String accessToken, String idFintechUmUser) {
		MarvelsLogUtil.getInstance().info("======V2添加通讯录认证成功节点流程信息，参数:" + loanId);
		AcLoanApplyNode applyNode = acLoanApplyNodeService.queryLastApplyNode(loanId);
		if (applyNode == null) {
			return FintechResult.getFailResult(ReturnCode.fail.getErrorCode(), "查询最新的节点信息为空");
		}
		String key = "addLinkManAuthNodeV2_" + loanId;
		boolean isNotLock = false;
		try {
			isNotLock = CacheUtils.isNotLock(key, loanId);
			if (isNotLock) {
				// 先将这个key设置过期时间
				CacheUtils.setExpire(key, 60);
				// 是复贷直接走完整个流程
				if(acLoanApplyInfoExtDragonService.isReLoan(loanId)){
					MarvelsLogUtil.getInstance().info("V2复贷授权完成流转节点：" + loanId);
					User user = UserUtils.getUser(accessToken, idFintechUmUser);
					if (user == null) {
						return FintechResult.getResult(ReturnCode.tokenInvalid.getErrorCode(), "登录超时，请重新登录！", null);
					}
					//1.判断是否已经实名验证,如果没有则驳回
					RealNameAuthentication realNameAuthentication = realNameAuthenticationService.queryByUserId(user.getId());
					if (realNameAuthentication == null) {
						return FintechResult.getResult(ErrorCode.NO_VERIFY, "请先去实名验证", null);
					}

					//防止重复提交
					AcLoanApplyInfo loan = loanInfoIDragonService.queryLoanBasicInfo(loanId);
					if(loan.getStatus().equals("K02")){
						return FintechResult.getFailResult(ReturnCode.fail.getErrorCode(), "请勿重复操作");
					}
					loanInfoIDragonService.updateLoanStatus(loanId, "K02",user.getRealName());

					AcLoanApplyNode acLoanApplyNode = new AcLoanApplyNode();
					acLoanApplyNode.setLoanId(loanId);
					acLoanApplyNode.setNodeCode(ApplyNode.LINKMAN_AUTH.getCode());
					acLoanApplyNode.setNodeMsg(ApplyNode.LINKMAN_AUTH.getMsg());
					// 将所有节点流转完成
					acLoanApplyNodeService.insertSelective(loanId, ApplyNode.LINKMAN_AUTH);
					acLoanApplyNodeService.insertSelective(loanId, ApplyNode.CARRIER_AUTH);
					if(acLoanApplyNodeService.isGoAlipay()){
						acLoanApplyNodeService.insertSelective(loanId, ApplyNode.ALIPAY_AUTH);
					}
					acLoanApplyNodeService.insertSelective(loanId, ApplyNode.REVIEW_DOING);
					// 发送到新核心
					asyncCallApi.sendLoanApplyMessage(loanId);
					AcLoanApplyInfo acLoanApplyInfoNew = new AcLoanApplyInfo();
					acLoanApplyInfoNew.setLoanId(loanId);
					acLoanApplyInfoNew.setGoNewMarvels(new Byte("1"));
					loanInfoIDragonService.input(acLoanApplyInfoNew);
			        MarvelsLogUtil.getInstance().info("=====V2复贷时将数据推送给新核心,loanId=" + loanId);
//					try {
//						EdcSharedDataDTO  dataDTO=new EdcSharedDataDTO();
//						dataDTO.setCreatedBy("system");
//						dataDTO.setCreatedDate(new Date());
//						dataDTO.setCustName(realNameAuthentication.getRealName());
//						dataDTO.setCustCardNo(realNameAuthentication.getIdentityCardNo());
//						dataDTO.setLoanId(loanId);
//						dataDTO.setMobileNo(user.getMobileNo());
//						dataDTO.setStatus("2");//申请
//						dataDTO.setSrc(loanId.substring(0, 3));
//						dataDTO.setUpdatedDate(new Date());
//						dataDTO.setUpdatedBy("system");
//						sharedDataMqProvideApi.synSharedDataUpdate(dataDTO);
//					} catch (Exception e) {
//						MarvelsLogUtil.getInstance().error(">>>>>>V2loanId"+loanId+"进件申请推送共享数据失败:",e);
//					}
				}else{
					MarvelsLogUtil.getInstance().info("V2非复贷授权完成流转节点：" + loanId);
					AcLoanApplyNode acLoanApplyNode = new AcLoanApplyNode();
					acLoanApplyNode.setLoanId(loanId);
					acLoanApplyNode.setNodeCode(ApplyNode.LINKMAN_AUTH.getCode());
					acLoanApplyNode.setNodeMsg(ApplyNode.LINKMAN_AUTH.getMsg());
					FintechResult result= addLoanApplyNode(acLoanApplyNode);
					if(!result.getErrorCode().equals("0")){
						return result;
					}
				}
			}
			return FintechResult.getSuccessResult(null);
		} catch (Exception e) {
			MarvelsLogUtil.getInstance().error(loanId + "V2添加节点流程信息异常", e);
			return FintechResult.getFailResult(ReturnCode.fail.getErrorCode(), "添加节点流程信息异常");
		} finally {
			if (!CacheUtils.isNotLock(key, loanId)) {// 如果是锁住的将所释放
				CacheUtils.del(key);
			}
		}
	}


	@Override
	public FintechResult addLoanApplyNode(AcLoanApplyNode acLoanApplyNode) {
		MarvelsLogUtil.getInstance().info("======添加节点流程信息，参数:" + acLoanApplyNode);
		try {
			if (acLoanApplyNode == null || StrUtil.isEmpty(acLoanApplyNode.getLoanId())) {
				return FintechResult.getFailResult(ReturnCode.fail.getErrorCode(), "贷款编号为空");
			}
			if (acLoanApplyNode.getNodeCode() == null || ApplyNode.notContainsCode(acLoanApplyNode.getNodeCode())) {
				return FintechResult.getFailResult(ReturnCode.fail.getErrorCode(), "节点流程状态不正确");
			}
			// 添加节点流程信息
			acLoanApplyNodeService.insertSelective(acLoanApplyNode);
			MarvelsLogUtil.getInstance().info("======添加节点流程信息成功");
			return FintechResult.getSuccessResult(null);
		} catch (Exception e) {
			MarvelsLogUtil.getInstance().error("添加节点流程信息异常", e);
			return FintechResult.getFailResult(ReturnCode.fail.getErrorCode(), "添加节点流程信息异常");
		}
	}

	@Override
	public FintechResult doApprove(String loanId) {
		MarvelsLogUtil.getInstance().info("======触发审核，参数:" + loanId);
		// 加锁 避免重复插入数据
		String key = "doApprove_" + loanId;
		boolean isNotLock = false;
		try {
			isNotLock = CacheUtils.isNotLock(key, loanId);
			if (isNotLock) {
				// 先将这个key设置过期时间
				CacheUtils.setExpire(key, 60);
				if (StrUtil.isEmpty(loanId)) {
					return FintechResult.getFailResult(ReturnCode.fail.getErrorCode(), "贷款编号为空");
				}
				AcLoanApplyNode applyNode = acLoanApplyNodeService.queryLastApplyNode(loanId);
				if (applyNode == null) {
					return FintechResult.getFailResult(ReturnCode.fail.getErrorCode(), "查询最新的节点信息为空");
				}

				loanInfoIDragonService.updateLoanStatus(loanId, "K02","");
		        // 发送到新核心
				asyncCallApi.sendLoanApplyMessage(loanId);

				AcLoanApplyInfo acLoanApplyInfo = new AcLoanApplyInfo();
				acLoanApplyInfo.setLoanId(loanId);
				acLoanApplyInfo.setGoNewMarvels(new Byte("1"));
				loanInfoIDragonService.input(acLoanApplyInfo);

		        MarvelsLogUtil.getInstance().info("======扭转新流程节点为审核中，参数:" + loanId);
				acLoanApplyNodeService.insertSelective(loanId, ApplyNode.REVIEW_DOING);

				MarvelsLogUtil.getInstance().info("======触发审核成功");
			}
			return FintechResult.getSuccessResult(null);
		} catch (Exception e) {
			MarvelsLogUtil.getInstance().error("触发审核异常,loanId=[" + loanId + "]", e);
			return FintechResult.getFailResult(ReturnCode.fail.getErrorCode(), "触发审核异常");
		} finally {
			if (!CacheUtils.isNotLock(key, loanId)) {// 如果是锁住的将所释放
				CacheUtils.del(key);
			}
		}
	}

	@Override
	public FintechResult showContract(String loanId) {
		MarvelsLogUtil.getInstance().info("======展示合同信息，参数:" + loanId);
		try {
			if (StrUtil.isEmpty(loanId)) {
				return FintechResult.getFailResult(ReturnCode.fail.getErrorCode(), "贷款编号为空");
			}
			// 贷款信息
			AcLoanApplyInfo loanInfo = loanInfoIDragonService.queryLoanBasicInfo(loanId);
			MarvelsLogUtil.getInstance().info("======贷款信息结果:" + JSON.toJSONString(loanInfo));
			if (loanInfo == null) {
				return FintechResult.getFailResult(ReturnCode.fail.getErrorCode(), "展示合同信息为空");
			}
			Map<String, Object> rtnMap = new HashMap<>();
			rtnMap.put("loanIdNo", loanInfo.getCustIdCard());
			rtnMap.put("loanName", loanInfo.getCustName());
			rtnMap.put("loanMoney", loanInfo.getLoanMoneyAct());
			rtnMap.put("loanDate", new SimpleDateFormat("yyyy-MM-dd").format(loanInfo.getApplyTime()));
			/*Map<String, Object> reqMap = new HashMap<String, Object>();
			reqMap.put("productType", loanInfo.getProductType());
			JsonResult<Map> jsonResult = newMarvelCoreService.getForObjectPost(MarvelURLConstant.PRODUCT_API_SERVICE_FEECODE, reqMap, Map.class);
			// 调用返回数据
			Map data = jsonResult.getData();*/

			com.marvels.product.productmanage.dto.McptProductDto paramDto = new com.marvels.product.productmanage.dto.McptProductDto();
			paramDto.setProductType(loanInfo.getProductType().toString());
			// 调用返回数据
			Map data = productTypeService.queryByConsultingFeeCode(paramDto);

			// 返回数据
			Map<String, Object> retMap = new HashMap<String, Object>();
			if(null != data){
				// 借款天数
				Integer applyTerms = loanInfo.getApplyTerms();
				String cycle = data.get("cycle") == null ? "" : (String) data.get("cycle");
				Integer cycleDay = 0;
				if(StrUtil.isNotEmpty(cycle)){
					if("A000".equals(cycle)){
						cycleDay = 1;
					}else if("A001".equals(cycle)){
						cycleDay = 7;
					}else if("A002".equals(cycle)){
						cycleDay = 14;
					}else if("A003".equals(cycle)){
						cycleDay = 15;
					}else if("A004".equals(cycle)){
						cycleDay = 30;
					}else if("A005".equals(cycle)){
						cycleDay = 90;
					}
				}
				if(null != applyTerms){
					applyTerms = applyTerms * cycleDay;
				}
				// 借款天数
				rtnMap.put("borDays", applyTerms);

			}
			// 获取贷款人信息
			AcLenderConfig acLenderConfig = acLenderConfigMapper.selectValid();
			if (acLenderConfig == null) {
				return FintechResult.getFailResult(ReturnCode.fail.getErrorCode(), "未配置贷款人信息");
			}
			rtnMap.put("lenderIdNo", acLenderConfig.getLenderIdNo());
			rtnMap.put("lenderName", acLenderConfig.getLenderName());
			MarvelsLogUtil.getInstance().info("======展示合同信息成功");
			return FintechResult.getSuccessResult(rtnMap);
		} catch (Exception e) {
			MarvelsLogUtil.getInstance().error("展示合同信息异常, loanId=" + loanId, e);
			return FintechResult.getFailResult(ReturnCode.fail.getErrorCode(), "展示合同信息异常");
		}
	}

	@Override
	public FintechResult getThirdLoanId(String loanId) {
		MarvelsLogUtil.getInstance().info("======获取第三方查询LOANID开始，参数:" + loanId);
		try {
			if (StrUtil.isEmpty(loanId)) {
				return FintechResult.getFailResult(ReturnCode.fail.getErrorCode(), "贷款编号为空");
			}
			// 扩展信息
			Map<String, String> extMap = acLoanApplyInfoExtDragonService.getExtInfoByLoanId(loanId);
			MarvelsLogUtil.getInstance().info("======获取扩展信息:" + JSON.toJSONString(extMap));
			if (extMap != null && "1".equals(extMap.get("reloan_flag"))) {
				MarvelsLogUtil.getInstance().info("=======复贷，取复贷LOANID=" + extMap.get("reloan_id"));
				return FintechResult.getSuccessResult(extMap.get("reloan_id"));
			}
			MarvelsLogUtil.getInstance().info("======获取第三方查询LOANID成功");
			return FintechResult.getSuccessResult(loanId);
		} catch (Exception e) {
			MarvelsLogUtil.getInstance().error("获取第三方查询LOANID异常, loanId=" + loanId, e);
			return FintechResult.getFailResult(ReturnCode.fail.getErrorCode(), "获取第三方查询LOANID异常");
		}
	}

	@Override
	public FintechResult confirmLoanExtension(LoanExtensionRecoreds loanExtensionRecoreds) {
		MarvelsLogUtil.getInstance().info("======确认展期，参数:" + loanExtensionRecoreds);
		try {
			if (loanExtensionRecoreds == null) {
				return FintechResult.getFailResult(ReturnCode.fail.getErrorCode(), "展期信息为空");
			}
			if (StrUtil.isEmpty(loanExtensionRecoreds.getLoanId())) {
				return FintechResult.getFailResult(ReturnCode.fail.getErrorCode(), "贷款编号不正确");
			}
			if (ExtensionType.notContainsCode(loanExtensionRecoreds.getExtensionType())) {
				return FintechResult.getFailResult(ReturnCode.fail.getErrorCode(), "展期类型不正确");
			}
			// 生成展期操作流水
			loanExtensionRecoreds.setReqNo("ZQ_" + System.currentTimeMillis() + "_" + RandomStringUtils.randomAlphanumeric(6));

			// 贷款信息
			AcLoanApplyInfo loanInfo = loanInfoIDragonService.queryLoanBasicInfo(loanExtensionRecoreds.getLoanId());
			MarvelsLogUtil.getInstance().info("======贷款信息结果:" + JSON.toJSONString(loanInfo));
			if (loanInfo == null || !"D01".equals(loanInfo.getStatus())) {
				return FintechResult.getFailResult(ReturnCode.fail.getErrorCode(), "当前节点不能发起展期操作");
			}

			// 调用财务进行展期操作
			/*Map<String, String> reqMap = new HashMap<>();
			reqMap.put("loanId", loanExtensionRecoreds.getLoanId());
			reqMap.put("type", loanExtensionRecoreds.getExtensionType());
			reqMap.put("requestNo", loanExtensionRecoreds.getReqNo());
			reqMap.put("s1PayerName", loanExtensionRecoreds.getS1PayerName());//姓名
			reqMap.put("s3PayerCardNo", loanExtensionRecoreds.getS3PayerCardNo());//身份证
			reqMap.put("s4PayerBankCardNo", loanExtensionRecoreds.getS4PayerBankCardNo());//银行卡号
			reqMap.put("s7BankMobile", loanExtensionRecoreds.getS7BankMobile());//手机号
			reqMap.put("t2SmsCode", loanExtensionRecoreds.getT2SmsCode());//验证码
			reqMap.put("bankName", loanExtensionRecoreds.getBankName());//银行名称
			reqMap.put("withholdWay", loanExtensionRecoreds.getWithholdWay());// 0 协议代扣  1 直接代扣(四要素代扣)
			JsonResult<LoanExtensionRecoreds> jsonResult = newMarvelCoreService.getForObjectPost(MarvelURLConstant.APPROVE_LOAN_API_EXTENSION_WITHHOLD, reqMap, LoanExtensionRecoreds.class);*/

			JsonResult<LoanExtensionRecoreds> jsonResult = new JsonResult<LoanExtensionRecoreds>();
			com.marvels.financial.loan.dto.ExtensionFunctionConditionDTO conditionDTO = new com.marvels.financial.loan.dto.ExtensionFunctionConditionDTO();
			conditionDTO.setLoanId(loanExtensionRecoreds.getLoanId());
			conditionDTO.setType(loanExtensionRecoreds.getExtensionType());
			conditionDTO.setRequestNo(loanExtensionRecoreds.getReqNo());
			conditionDTO.setS1PayerName(loanExtensionRecoreds.getS1PayerName());
			conditionDTO.setS3PayerCardNo(loanExtensionRecoreds.getS3PayerCardNo());
			conditionDTO.setS4PayerBankCardNo(loanExtensionRecoreds.getS4PayerBankCardNo());
			conditionDTO.setS7BankMobile(loanExtensionRecoreds.getS7BankMobile());
			conditionDTO.setT2SmsCode(loanExtensionRecoreds.getT2SmsCode());
			conditionDTO.setBankName(loanExtensionRecoreds.getBankName());
			conditionDTO.setWithholdWay(loanExtensionRecoreds.getWithholdWay());
			try {
				PaymentResponse paymentResponse = extensionFunctionApi.extensionWithhold(conditionDTO);
				jsonResult.setErrorCode(ErrorCode.SUCCESS);
				LoanExtensionRecoreds data = new LoanExtensionRecoreds();
				BeanUtil.copyProperties(paymentResponse, data);
				jsonResult.setData(data);
				jsonResult.setMessage("成功");
			} catch (MarvelsBusinessException e) {
				MarvelsLogUtil.getInstance().error(">>>>>>展期功能代扣FAIL:", e);
				return FintechResult.getFailResult(ReturnCode.fail.getErrorCode(), e.getMessage());
			}

			MarvelsLogUtil.getInstance().info("========APPROVE_LOAN_API_EXTENSION_WITHHOLD：" + JSON.toJSONString(jsonResult));
			if (!"0".equals(jsonResult.getErrorCode())) {
				MarvelsLogUtil.getInstance().info("======新核心确认展期操作失败");
				return FintechResult.getFailResult(ReturnCode.fail.getErrorCode(), jsonResult.getMessage());
			}
			// 调用返回数据
			LoanExtensionRecoreds loanExtensionResult = jsonResult.getData();
			/*
			 * 错误码 0成功 -1失败 -2超时 -3异常 1交易处理中 -5 交易重复 -6 验签不一致
			 * 和佩文确认，展期确认操作，0和-1之外的状态码全部当成处理中，具体结果通过查询来获取
			 */
			if ("0".equals(loanExtensionResult.getCode())) {
				loanExtensionRecoreds.setCode(ExtensionResult.SUCCESS.getCode());
				loanExtensionRecoreds.setMsg(ExtensionResult.SUCCESS.getMsg());
			} else if ("-1".equals(loanExtensionResult.getCode())) {
				loanExtensionRecoreds.setCode(ExtensionResult.FAIL.getCode());
				loanExtensionRecoreds.setMsg(ExtensionResult.FAIL.getMsg());
			} else {
				loanExtensionRecoreds.setCode(ExtensionResult.PROCESSING.getCode());
				loanExtensionRecoreds.setMsg(ExtensionResult.PROCESSING.getCode());
			}
			MarvelsLogUtil.getInstance().info("======确认展期操作成功");
			return FintechResult.getSuccessResult(loanExtensionRecoreds);
		} catch (Exception e) {
			MarvelsLogUtil.getInstance().error("确认展期操作异常,loanExtensionRecoreds=" + loanExtensionRecoreds, e);
			return FintechResult.getFailResult(ReturnCode.fail.getErrorCode(), "确认展期操作异常");
		}
	}

	@Override
	public FintechResult queryLoanExtensionByLoanId(String loanId) {
		MarvelsLogUtil.getInstance().info("======通过loanId查询展期信息，参数:" + loanId);
		List<LoanExtensionRecoreds> rtnList = new ArrayList<>();
		try {
			// 调用财务进行展期操作
			/*Map<String, String> reqMap = new HashMap<>();
			reqMap.put("loanId", loanId);
			JsonResult<JSONArray> jsonResult = newMarvelCoreService.getForObjectPost(MarvelURLConstant.APPROVE_LOAN_API_EXTENSION_RECORDS_QUERY, reqMap, JSONArray.class);*/
			com.marvels.financial.loan.dto.ExtensionFunctionConditionDTO conditionDTO = new com.marvels.financial.loan.dto.ExtensionFunctionConditionDTO();
			conditionDTO.setLoanId(loanId);
			List<McfePaymentWithholdDetailDTO> detailDTOs = extensionFunctionApi.extensionRecordsQuery(conditionDTO);
			JSONArray data= JSONArray.parseArray(JSON.toJSONString(detailDTOs));
			JsonResult<JSONArray> jsonResult = new JsonResult<JSONArray>();
			jsonResult.setMessage("成功");
			jsonResult.setErrorCode(ErrorCode.SUCCESS);
			jsonResult.setData(data);


			MarvelsLogUtil.getInstance().info("========APPROVE_LOAN_API_EXTENSION_RECORDS_QUERY：" + JSON.toJSONString(jsonResult));
			if (!"0".equals(jsonResult.getErrorCode())) {
				MarvelsLogUtil.getInstance().info("======新核心展期记录查询失败");
				return FintechResult.getFailResult(ReturnCode.fail.getErrorCode(), jsonResult.getMessage());
			}
			// 调用返回数据
			JSONArray jsonAry = jsonResult.getData();
			if (Collections3.isNotEmpty(jsonAry)) {
				DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
				for (int i = 0; i < jsonAry.size(); i++) {
					JSONObject json = jsonAry.getJSONObject(i);
					LoanExtensionRecoreds recoreds = new LoanExtensionRecoreds();
					recoreds.setLoanId(loanId);
					recoreds.setExtensionDays(json.getInteger("extensionDay"));
					recoreds.setExtensionMoney(json.getBigDecimal("amount"));
					recoreds.setReqNo(json.getString("transctionSeq"));
					recoreds.setStartDate(dateFormat.format(json.getDate("createdDate")));
					/*
					 * 和佩文确认，status 1交易中   2代扣成功  9代扣失败
					 */
					if ("2".equals(json.getString("status"))) {
						recoreds.setCode(ExtensionResult.SUCCESS.getCode());
						recoreds.setMsg(ExtensionResult.SUCCESS.getMsg());
					} else if ("9".equals(json.getString("status"))) {
						recoreds.setCode(ExtensionResult.FAIL.getCode());
						recoreds.setMsg(ExtensionResult.FAIL.getMsg());
					} else {
						recoreds.setCode(ExtensionResult.PROCESSING.getCode());
						recoreds.setMsg(ExtensionResult.PROCESSING.getMsg());
					}
					rtnList.add(recoreds);
				}
			}
			MarvelsLogUtil.getInstance().info("======展期记录查询成功");
			return FintechResult.getSuccessResult(rtnList);
		} catch (Exception e) {
			MarvelsLogUtil.getInstance().error("展期记录查询异常, loanId=[" + loanId + "]", e);
			return FintechResult.getFailResult(ReturnCode.fail.getErrorCode(), "展期记录查询异常");
		}
	}


	/**
	 * 保存紧急联系人
	 * @param loanApplyLinkmanList
	 * @param userId
	 * @return
	 */
	@Override
	public FintechResult saveRelation(List<MclaLoanApplyLinkmanDTO> loanApplyLinkmanList, Integer userId) {
		// 获取当前贷款申请编号
		RealNameAuthentication realNameAuthentication = realNameAuthenticationService.queryByUserId(userId);
		String loanId = loanInfoIDragonService.selectCustApplyingLoanId(realNameAuthentication.getIdentityCardNo());
		try {
			boolean check = true;
			for (MclaLoanApplyLinkmanDTO mclaLoanApplyLinkmanDTO : loanApplyLinkmanList) {
				if(mclaLoanApplyLinkmanDTO == null || ContactsTypeEnum.getNameById(mclaLoanApplyLinkmanDTO.getRelationId()) == null
						|| mclaLoanApplyLinkmanDTO.getLinkmanName() == null
						|| mclaLoanApplyLinkmanDTO.getLinkmanMobile() == null
						|| !Validator.isMobile(mclaLoanApplyLinkmanDTO.getLinkmanMobile())){
					check = false;
					break;
				}
				mclaLoanApplyLinkmanDTO.setLoanId(loanId);
				mclaLoanApplyLinkmanDTO.setIsEmergencyLinkman("1");
			}
			if(!check){
				return FintechResult.getFailResult(ReturnCode.fail.getErrorCode(), "数据格式错误");
			}
			// 保存数据
			mclaLinkmanMobileApi.saveLinkmanMobile(loanApplyLinkmanList);
			acLoanApplyNodeService.insertSelective(loanId, ApplyNode.SAVE_RELATION);
			return FintechResult.getSuccessResult(null);
		} catch (Exception e) {
			MarvelsLogUtil.getInstance().error("保存紧急联系人异常, loanId=[" + loanId + "]", e);
			return FintechResult.getFailResult(ReturnCode.fail.getErrorCode(), "保存紧急联系人异常");
		}

	}

	/* (non-Javadoc)
	 * @see com.dragon.app.ykd.service.ClientAppService#contractContent(java.lang.String)
	 */
	@Override
	public FintechResult contractContent(String loanId) {
		FintechResult result = FintechResult.getSuccessResult(null);
		try {
			List<ProtocolTemplateInfoDTO> templateInfoList = acLoanApplyInfoService.contractContent(loanId);
			if(CollectionUtils.isEmpty(templateInfoList)) {
				return FintechResult.getFailResult(ReturnCode.fail.getErrorCode(), "暂未获取到协议内容，请稍后再试");
			}
			List<Map<String,String>> resultList = new ArrayList<Map<String,String>>();
			templateInfoList.forEach( protocolTemplateInfoDTO -> {
				Map<String,String> map = new HashMap<String,String>();
				map.put("contractName", protocolTemplateInfoDTO.getContractName());
				map.put("contractContent", protocolTemplateInfoDTO.getContractContent());
				resultList.add(map);
			});
			result.setData(resultList);
		} catch (MarvelsBusinessException e) {
			return FintechResult.getFailResult(ReturnCode.fail.getErrorCode(), "获取协议内容缓慢，请稍后再试");
		}
		return result;
	}

	@Override
	public FintechResult jiaYinJinKApplyLoan(JiaYinJinKApplyLoanDTO jiaYinJinKApplyLoanDTO) {
		MarvelsLogUtil.getInstance().info("接受请求api/v1/applyInfo,进件参数:"+JSON.toJSONString(jiaYinJinKApplyLoanDTO));

		Map<String, String> resultMap = null;
		try {

			if(StringUtils.isEmpty(jiaYinJinKApplyLoanDTO.getProductId()) ||
					!jiaYinJinKApplyLoanDTO.getProductId().equals("JiaYinJinK")){
				return FintechResult.getResult(ErrorCode.FAIL, "ProductId参数异常，请核实", null);
			}

			int count = loanInfoIDragonService.queryJiaYinJinKApplyLoanBasicInfo(jiaYinJinKApplyLoanDTO.getRefOrderId());
			if(count>0){
				return FintechResult.getResult(ErrorCode.FAIL, "RefOrderId参数异常，请核实,该订单已上送，无需重复操作", null);
			}

			//1初始化保存贷款信息 AcLoanApplyInfo
			String loanId = loanInfoIDragonService.generateLoanId();
			AcLoanApplyInfo acLoanApplyInfo = JiaYinJinKApplyLoanDTO.getAcLoanApplyInfo(jiaYinJinKApplyLoanDTO);
			acLoanApplyInfo.setMerchantCode(jiaYinJinKApplyLoanDTO.getRefOrderId());
			MarvelsLogUtil.getInstance().info("4.ClientAppServiceImpl.applyLoan" + System.currentTimeMillis());

			acLoanApplyInfo.setPositionType(jiaYinJinKApplyLoanDTO.getPositionType());
			acLoanApplyInfo.setProvinceId(jiaYinJinKApplyLoanDTO.getProvinceId());
			acLoanApplyInfo.setProvinceName(jiaYinJinKApplyLoanDTO.getProvinceName());
			acLoanApplyInfo.setCityId(jiaYinJinKApplyLoanDTO.getCityId());
			acLoanApplyInfo.setCityName(jiaYinJinKApplyLoanDTO.getCityName());
			acLoanApplyInfo.setAreaId(jiaYinJinKApplyLoanDTO.getAreaId());
			acLoanApplyInfo.setAreaName(jiaYinJinKApplyLoanDTO.getAreaName());
			acLoanApplyInfo.setAddress(jiaYinJinKApplyLoanDTO.getAddress());
			acLoanApplyInfo.setCompanyName(jiaYinJinKApplyLoanDTO.getCompanyName());
			acLoanApplyInfo.setCompanyType(jiaYinJinKApplyLoanDTO.getCompanyType());

			acLoanApplyInfo.setCompanyProvinceId(jiaYinJinKApplyLoanDTO.getCompanyProvinceId());
			acLoanApplyInfo.setCompanyProvinceName(jiaYinJinKApplyLoanDTO.getCompanyProvinceName());
			acLoanApplyInfo.setCompanyCityId(jiaYinJinKApplyLoanDTO.getCompanyCityId());
			acLoanApplyInfo.setCompanyCityName(jiaYinJinKApplyLoanDTO.getCompanyCityName());
			acLoanApplyInfo.setCompanyAreaId(jiaYinJinKApplyLoanDTO.getCompanyAreaId());
			acLoanApplyInfo.setCompanyAreaName(jiaYinJinKApplyLoanDTO.getCompanyAreaName());
			acLoanApplyInfo.setCompanyAddress(jiaYinJinKApplyLoanDTO.getCompanyAddress());
			acLoanApplyInfo.setLiveTypeId(jiaYinJinKApplyLoanDTO.getLiveType());
			acLoanApplyInfo.setEducationLevel(jiaYinJinKApplyLoanDTO.getEducation());
			acLoanApplyInfo.setMarriageId(jiaYinJinKApplyLoanDTO.getMarriages());
			acLoanApplyInfo.setMonthlyIncomeId(jiaYinJinKApplyLoanDTO.getMonthIncome());
			acLoanApplyInfo.setOfficePhone(jiaYinJinKApplyLoanDTO.getOfficeTel());
			acLoanApplyInfo.setWorkYearsId(jiaYinJinKApplyLoanDTO.getWorkYear());
			acLoanApplyInfo.setOrgId(jiaYinJinKApplyLoanDTO.getRefOrderId());

			acLoanApplyInfo.setLoanId(loanId);

			if(jiaYinJinKApplyLoanDTO.getContactList()!=null && jiaYinJinKApplyLoanDTO.getContactList().size()>0){
				for (JiaYinJinKContactDTO jiaYinJinKContactDTO:jiaYinJinKApplyLoanDTO.getContactList()) {
					AcLoanApplyLinkman acLoanApplyLinkman = new AcLoanApplyLinkman();
					acLoanApplyLinkman.setLoanId(loanId);
					acLoanApplyLinkman.setLinkmanName(jiaYinJinKContactDTO.getContactName());
					acLoanApplyLinkman.setLinkmanMobile(jiaYinJinKContactDTO.getContactMobile());
					acLoanApplyLinkman.setRelationName(jiaYinJinKContactDTO.getRelationName());
					loanApplyLinkmanRepository.insertSelective(acLoanApplyLinkman);
				}
			}

			//2.查询产品类型是否存在
			McptProductTypeDto mcptProducTypeDto = new McptProductTypeDto();
			mcptProducTypeDto.setId(3);//------嘉银现金分期
			mcptProducTypeDto = productTypeService.queryOnlineProduct(mcptProducTypeDto);
			if(StringUtils.isBlank(mcptProducTypeDto.getProductType())) {
				return FintechResult.getResult(ErrorCode.FAIL, "申请产品已下线，请确认", null);
			}

			//3查找产品小类信息
			McptProductInfoDTO mcptProductInfoDTO = new McptProductInfoDTO();
			mcptProductInfoDTO.setTerm(String.valueOf(jiaYinJinKApplyLoanDTO.getLoanTerm()));//默认先查询一期的
			mcptProductInfoDTO.setProductType(mcptProducTypeDto.getProductType());
			List<McptProductInfoDTO> productInfoList = productConsumerService.selectProductInfo(mcptProductInfoDTO);


			acLoanApplyInfo.setProductType(mcptProducTypeDto.getProductType());
			acLoanApplyInfo.setProductId(mcptProducTypeDto.getProductType());
			acLoanApplyInfo.setProductName(productInfoList.get(0).getProductTypeName());
			acLoanApplyInfo.setProductTypeName(productInfoList.get(0).getProductTypeName());
			// 查询这个用户手机号的归属地
			Map<String, Object> selectAttributionByMobileSix = loanInfoIDragonService
					.selectAttributionByMobileSix(jiaYinJinKApplyLoanDTO.getMobilePhone().substring(0, 7));
			if (selectAttributionByMobileSix != null) {
				Object provinceObj = selectAttributionByMobileSix.get("province");
				Object cityObj = selectAttributionByMobileSix.get("city");
				if (provinceObj != null) {
					acLoanApplyInfo.setMobileAffiliationProvince(provinceObj.toString());
				}
				if (cityObj != null) {
					acLoanApplyInfo.setMobileAffiliationCity(cityObj.toString());
				}
			}
			MarvelsLogUtil.getInstance().info("5.ClientAppServiceImpl.applyLoan" + System.currentTimeMillis());

			acLoanApplyInfo.setCreditLvl("A");
			acLoanApplyInfo.setChannelType("103");
			acLoanApplyInfo.setUserId("26");
			acLoanApplyInfo.setMobileNum(jiaYinJinKApplyLoanDTO.getMobilePhone());
			acLoanApplyInfo.setMerchantCode(jiaYinJinKApplyLoanDTO.getRefOrderId());
			loanInfoIDragonService.input(acLoanApplyInfo);

			// 4\获取进件内容同步到 McamLoanApplyInfo
			McamLoanApplyInfoDTO originalLoan = loanApplyDataSynchronizeService.synchronizeLoanApplyInfo(loanId);
			originalLoan.setContractNo(jiaYinJinKApplyLoanDTO.getContractNo());
			loanInfoIDragonService.updateJiaYinJinKApplyLoanResult(jiaYinJinKApplyLoanDTO.getRefOrderId(), loanId);

			resultMap = new HashMap<String, String>(2);
			resultMap.put("loanId", loanId);
			// 进件成功，添加新流程节点信息
			MarvelsLogUtil.getInstance().info("======进件成功，初始化新流程节点，参数:" + loanId);
			acLoanApplyNodeService.insertSelective(loanId, ApplyNode.LOAN_REPAYMENT);
		} catch (Exception e) {
			MarvelsLogUtil.getInstance().error("=====apply/loan=====", e);
			return FintechResult.getResult(ErrorCode.FAIL, "系统异常", null);
		}
		return FintechResult.getResult(ErrorCode.SUCCESS, "操作成功", resultMap);
	}

}
